How to set where in relation Laravel?

房东的猫 提交于 2019-12-01 08:21:00

问题


I use the following construction for joining tables: with("attachments", "offers.publisher").

public function publisher()
    {
        return $this->belongsTo("App\User", "user_id", "id");
    }

How to join publisher relation only when offers.status = 1?

In other words I need to use publisher by condition Where

I tried also this:

 $announcements = Announcement::whereHas('offers', function($q) {
            $q->with("publisher")->where('status', 1);
        })->get();

回答1:


The best way would to just have two definitions, publishers for all publishers, and active_publishers for those with status = 1:

public function publisher()
{
    return $this->belongsTo("App\User", "user_id", "id");
}

public function active_publisher()
{
    return $this->publisher()->where('status', 1);
}

Use with $object->active_publisher()->get();




回答2:


Here is link that can help you:

Please check this:

Eloquent where condition based on a "belongs to" relationship

Also you can do like this:

Suppose you have a post modal and each post has many comment. So can get the condition matching post comments by as following with where conditions

 public function comments()
{
    return $this->hasMany('App\Comment');
}

 App\Post::find(1)->comments()->where('title', 'foo')->get();

Thanks



来源:https://stackoverflow.com/questions/42305460/how-to-set-where-in-relation-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!