[英]Laravel - Get records collection, if not exists in another table
I need to get all records from table IF these records not exists in another table, eg 我需要从表中获取所有记录,如果这些记录在另一个表中不存在,例如
Table 'Cars' 表“汽车”
| ID | Name_of_car
+----+----------------
| 1 .| Toyota
+----+----------------
| 2 .| Ford
Table 'Crashed_cars' 表格“ Crashed_cars”
| car_id | crash_date
+--------+----------------
| 1 .....| 22-02-2016
Now I want to get all not crashed cars - how can I do this? 现在我想让所有未撞车的人-我该怎么做?
At the moment I use a loop, but due to the number of entries (about 3000) I would have to use the direct collection. 目前,我使用循环,但是由于条目数(大约3000),我将不得不使用直接集合。 Here is my query:
这是我的查询:
Cars::select( 'id', 'firstname', 'lastname', 'car', 'color' )->get();
The best way is probably to get the ids of all crashed cars, and then searching for all other cars. 最好的方法可能是获取所有坠毁汽车的ID,然后搜索所有其他汽车。 In other words, something like this:
换句话说,是这样的:
$crashedCarIds = CrashedCar::pluck('car_id')->all();
$cars = Car::whereNotIn('id', $crashedCarIds)->select(...)->get();
You could also get the same result with one single query, which will increase the speed of your action. 您也可以通过一个查询获得相同的结果,这将提高操作速度。
One could use a FULL OUTER JOIN to achieve this, like this example from the following article: 可以使用FULL OUTER JOIN来实现这一点,就像下面文章中的示例一样:
select * from dbo.Students S FULL OUTER JOIN dbo.Advisors A ON S.Advisor_ID=A.Advisor_ID where A.Advisor_ID is null
Article: http://www.datamartist.com/sql-inner-join-left-outer-join-full-outer-join-examples-with-syntax-for-sql-server no. 文章: http : //www.datamartist.com/sql-inner-join-left-outer-join-full-outer-join-examples-with-syntax-for-sql-server no。 6.
6。
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.