在Eloquent ORM中进行MINUS操作

时间:2014-04-13 14:24:32

标签: laravel eloquent

使用Eloquent ORM是否有来自SQL的等效MINUS操作?

例如

$ model1 = Model :: where('some constraints applied') $ model2 = Model :: where('some constraints applied')

我想获得$ model1中存在但不包含在$ model2

中的所有模型

2 个答案:

答案 0 :(得分:5)

seblaze的答案看起来不错,但它会运行3个查询。另一个选项是Collection对象的diff()方法:

$result = $model1->diff($model2);

在使用2个查询从数据库中获取数据之后,这是有效的,但是完整的数据集(除非有更多数据取决于您应用的约束')。

答案 1 :(得分:2)

我认为最简单的方法是:

//Get the id's of first model as array
$ids1 = $model1->lists('id');

//get the id's of second models as array
$ids2 = $model2->lists('id');

//get the models
$models = Model::whereIn('id',$ids1)->whereNotIn('id',$ids2)->get();

这不是经过测试的代码,请阅读有关雄辩查询的更多信息here