简体   繁体   中英

laravel: hasmany error when find is null

i have a problem.that my hasMany relationship returns error.

this is controller :

public function test()
{
   $a = Province::find(410)->test;
}

and this is my model:

public function test()
{
   return $this->hasMany('App\Http\Models\Places\City','province');
}

then if my Province::find(410) is null

the program will throw an error exception like this:

Whoops, looks like something went wrong.

1/1
FatalThrowableError in Province.php line 127:
Call to a member function hasManyThrough() on null
in Province.php line 127
at Province::get_area_by_province_id('410') in CommonController.php line 66

enter image description here

but when find has result . the program running no problem.

so... what should i do?

i have no idea!!!

please help me!!!

thanks!!!!

You should check if the ID you are providing to the find method is not null

OR

Consider using laravel's other method findOrFail which will throw ModelNotFoundException if no results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM