如何设置Laravel的关系?

时间:2017-02-17 18:56:42

标签: laravel laravel-5.4

我使用以下构造来连接表:with("attachments", "offers.publisher").

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

如何仅在publisher时加入offers.status = 1关系?

换句话说,我需要按条件使用publisher

我也尝试了这个:

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

2 个答案:

答案 0 :(得分:3)

最好的方法是只有两个定义,publishers适用于所有发布商,active_publishers适用于status = 1的定义:

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

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

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

一起使用

答案 1 :(得分:1)

以下是可以帮助您的链接:

请检查:

Eloquent where condition based on a "belongs to" relationship

你也可以这样做:

假设您有一个帖子模态,每个帖子都有很多评论。因此可以通过以下条件获得条件匹配后评论

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

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

由于