Php 拉雷维尔雄辩而复杂的关系
我有两个表,用户和作业。用户拥有一个作业: 从用户模型:Php 拉雷维尔雄辩而复杂的关系,php,laravel,laravel-5,eloquent,relationship,Php,Laravel,Laravel 5,Eloquent,Relationship,我有两个表,用户和作业。用户拥有一个作业: 从用户模型: 公共函数getJobs(){ 返回$this->belongsTo('App\Jobs','operative\u id','id'); } 公共函数getUncompleteJobs(){ 返回$this->belongsTo('App\Jobs','operative\u id','id')) ->其中('jobStatus_id','=',1); } 这很好,但是作业在一个名为“status\u id”的字段中有一个状态(comp
公共函数getJobs(){
返回$this->belongsTo('App\Jobs','operative\u id','id');
}
公共函数getUncompleteJobs(){
返回$this->belongsTo('App\Jobs','operative\u id','id'))
->其中('jobStatus_id','=',1);
}
这很好,但是作业在一个名为“status\u id”的字段中有一个状态(completed、pending等),我想进一步细化getJobs(),这样它只返回那些status\u id等于2的作业
可能是我太胖了
从评论中编辑:
$op=App\User::where('client\u id',$us->getCompany->id)
->其中(“有效”,1)
->orderby('名称')
->其中('active',1)
->带('getIncompleteJobs'))
->get();
您可以创建关系,他们可以在另一个方法中使用您想要的任何条件来调用它
就像这样:
public function jobs()
{
return $this->belongsTo('App\Jobs','operative_id','id');
}
public function completedJobs()
{
return $this->jobs()->where('status_id', '=', 2);
}
您应该能够在其中添加一个
->('status_id','=',2)代码>到您的->belongsTo()
;看看这是否有效。->其中('jobStatus_id','=',1)代码>应该是状态\u id
?另一件事jobs
(getJobs()
和GetUncompleteJobs()
)表明将返回许多结果,但您只返回1(belongsTo()
返回单个记录或null
),并且您的型号名称App\jobs
应为单数Job
。。。检查您的命名约定。关系似乎总是空的。使用原始sql可能更好,但雄辩更简洁。不能在关系中使用->get()
,否则使用('completedJobs')
调用->将返回错误。(它需要一个Builder
类,->get()
将其转换为集合
)@timleis我忘了首先添加->get()
,但我后来编辑了它。但无论如何,谢谢你的提醒。:)对不起,这是我的错别字。没有get。是的,如果您调用User::first()->completedJobs()
(使用()
),但破坏了将其用作属性(用户::first()->completedJobs;
)或即时加载(->使用(“completedJobs”)
)或附加条件(用户::first()->completedJobs()->其中(…);
)