문제

In short, when I pull a record using php activerecord, I'd like to check that it exists before moving forward. There has to be an easier way to do this as each situation seems to be different and I'm not actually sure any of them are working correctly.

For example:

$var = Model::find_by_pk("something");

if (!empty($var)) { ... //record exists }

Will that catch all exceptions or if the record returns no rows at all for a single record pull?

Then I've tried this:

if (count($var->errors) == 0) { ... //records exist }

This seems to work on resultsets, but not single record pulls. I get an exception of trying to reference an object that doesn't exist.

I see the Model::exists() but does that mean I need to go back through and change all my activerecord calls? (http://www.phpactiverecord.org/docs/ActiveRecord/Model#methodexists)?

To sum up, what is a simple way (preferably universal and/or bullet proof) to check that a php.activerecord result has data?

도움이 되었습니까?

해결책

It should be enough to do

$var = Model::find_by_pk("something");
if($var){
    //winning
}else{
    //not found
}

The reason you can't do if (count($var->errors) == 0) is that when you don't get a hit, $var is not an object so you cannot check the errors for it.

Mind you that if you do find you'll get an exception if it doesn't exist, instead of just no result:

 try{
     $var = Model::find($id);
 }catch (\Exception $e){
      //not found
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top