问题
I have various relationships within my Eloquent
Models
that look like this:
public function main_image()
{
return $this->hasOne(Media::class, 'id', 'main_image_id');
}
However, it will run a SQL query if the main_image_id
is null or 0, so I end up with a number of queries like this:
select * from `media` where `media`.`id` is null and `media`.`id` is not null limit 1
Which obviously will not return anything, but still wastes resources. Is there any way of automatically checking for that?
Currently what I do is have a method, like hasMainImage()
, that checks that main_image_id
is not null and not 0, but a lot of the current system already uses the relationships, and I was wondering if I can add the check to the relationship method itself?
I have tried adding a check to it and return null
if the column has no real value, but I've got an Exception
that it has to return a Relation object. Or if I'm trying to Eager load it, I receive following error:
Call to a member function addEagerConstraints() on null
public function main_image()
{
if (!$this->main_image_id) {
return null;
}
return $this->hasOne('App\Modules\Media\Models\Media', 'id', 'main_image_id');
}
Thanks for your help!
EDIT: A perhaps more clear example:
$page = Page::find(1);
var_dump($page->main_image); // This will run a query as shown above that is guaranteed to return nothing
// Since at this point system knows that $page->main_image_id is 0 or null, I would like to use that to not run the query and automatically set $page->main_image to null
回答1:
You declare your relations in wrong order, Eloquent documentation is clear about this.
The entity that does no make sense by itself (without its "parent" you may say) should incorporate "belongsTo" relation (as documentation says inverse).
For demonstration lets say you have User model and you have many details about that user so you create Detail model.
Now User model should have detail relation:
public function detail() {
return $this->hasOne('App\Detail', 'user_id', 'id'); //you can see the difference here from your code sample, you have 2nd and 3rd parameter reversed
}
And Detail model should have user relation:
public function user()
{
return $this->belongsTo('App\User');
}
来源:https://stackoverflow.com/questions/44699673/laravel-eloquent-do-not-run-relationship-query-if-column-value-is-null-or-0