【问题标题】:Laravel 5.5 - get data from model where realated model has no data in specific monthLaravel 5.5 - 从实际模型在特定月份没有数据的模型中获取数据
【发布时间】: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() 方法混合使用

标签: php laravel


【解决方案1】:

你可以这样使用whereHas

House::whereHas('consumers' , function($query){
 $query->whereMonth('created_at' , '<>' , Carbon::now()->format('m'));
})->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多