【发布时间】:2019-04-02 10:36:09
【问题描述】:
我正在尝试从特定模型中获取一些数据,其中相关模型在当月没有数据。
有点像
Select * FROM houses
JOIN customers
WHERE "there is no customer for the current month;
但是在 Laravel 中。
我尝试了多种方法,但无法成功。
我有一个house 表。
房子表有很多customers。
现在我想获取当前月份没有customer 的所有houses。
我尝试了类似的方法:
House::whereMonth('House.customers.created_at', Carbon::now()->format('m'))->get();
对我有用的一个解决方案是:
$houses= House::all();
$customers = Customer::whereNotExists(function($query) use ($houses){
$query->whereMonth('created_at', Carbon::now()->format('m'));
})->get();
有人有更清洁的方法吗?
SQL表结构:
客户:
'id', 'house_id', 'name', 'created_at','updated_at'
房子:
'id', 'name', 'created_at','updated_at'
现在我想获取当月没有客户的所有房屋
【问题讨论】:
-
这是一个很好的解决方案
-
好吧,我知道我看到只有客户数据和真实房屋数据。我想反其道而行之。我应该说我只想要房屋数据。我只需要客户数据进行检查。
-
能否添加sql表结构?
-
我做到了:) ......
-
我认为您可以将
hasMany()与whereMonth()方法混合使用