如何设置关系Laravel? [英] How to set where in relation Laravel?

查看:69
本文介绍了如何设置关系Laravel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下构造用于联接表:with("attachments", "offers.publisher").

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

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

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

换句话说,我需要根据条件Where使用publisher

In other words I need to use publisher by condition Where

我也尝试过这个:

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

推荐答案

最好的方法是只有两个定义,publishers用于所有发布者,active_publishers用于具有status = 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);
}

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

这篇关于如何设置关系Laravel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆