[英]Laravel/Eloquent - Query - Select with relationship
Models 楷模
class Model1 extends Eloquent {
public function model2() {
return $this->hasOne('Model2');
}
}
class Model2 extends Eloquent {
public function model1() {
return $this->belongsTo('Model1');
}
}
Query I want 我要查询
I want to get all instances from Model1
which do not have a Model2
. 我想从
Model1
获得所有没有 Model2
实例。 In other words, there isn't any reference to that Model1
id
in Model2
table column model1_id
. 换句话说,在
Model2
表列model1_id
没有任何对该Model1
id
model1_id
。
This could be achieved with a foreach
loop, iterating all the Model1
and checking if the model2
atributte is null . 这可以通过
foreach
循环,迭代所有Model1
并检查model2
属性是否为null来实现 。 But I want to do it with Eloquent queries. 但是我想通过口才查询来做到这一点。
You might try something like 您可以尝试类似
Model1::has('model2', '=', 0)->get();
See: Laravel Docs - Eloquent - Querying Relations 请参阅: Laravel文档-雄辩的-查询关系
Update: 更新:
Model1::doesntHave('model2')->get();
This might be it: 可能是这样:
$ids = Model2::where('model1_id', null)->lists('id');
$result = Model1::whereIn('id', $ids)->get();
edit: 编辑:
I need to learn to read better :) I see that this is not it. 我需要学习阅读更好:)我看到不是这样。
edit2: 编辑2:
This might be it. 可能就是这样。 I havent tested it, but if there is an error then it should be easy to fix it!
我还没有测试过,但是如果有错误,那就很容易修复! (With the help of lagbox on IRC channel #laravel)
(借助IRC频道#laravel上的lagbox)
edit3: 编辑3:
Okey, so after discussing it on #laravel with lagbox there is a even better way... see his answer Okey,所以在与lagbox在#laravel上讨论之后,还有一个更好的方法...看他的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.