php - Laravel Eloquent 困难关系查询

标签 php mysql laravel orm eloquent

我是一个 friend 的系统,但偶然发现了一个小问题。 我有 3 个模型(customerCard、customerCardComment 和 customerCardFollowup)。

如果您看到下图以了解我想要实现的目标,那就更好了。正如您所看到的,我试图获得一个结果,其中我得到一个 customerCard 模型,其中已售字段等于 0,并且 customerCard 模型没有 customerCardComment 模型,其中类型字段等于 1,2 或 3,并且 customerCard 也没有任何 customerCardFollowup。

数据库: 客户卡 客户卡评论 customer_card_followups

评论和后续表都与 customer_cards 中的 ID 字段相关。两者都有外键 customer_card_id。

有办法实现这个查询吗?还是我迷路了? 提前致谢。

enter image description here

最佳答案

Laravel 的 whereHas 接受第三个和第四个参数。第三个参数是针对结果集的 count 的比较运算符,第四个参数是要比较的number。这将解决第一个问题:

CustomerCard::where(function($query){
    $query->where('sold', 0)
         ->whereHas('customerCardComment', function($query){
             return $query->whereIn('type', [1,2,3]);
         }, '=', 0);
});

接下来,您可以使用 ->has() 来计算从关系返回的记录数,这将解决您的第二个问题:

CustomerCard::where(function($query){
    $query->where('sold', 0)
         ->whereHas('customerCardComment', function($query){
             return $query->whereIn('type', [1,2,3]);
         }, '=',  0)
         ->has('customerCardFollowup', '=', 0);
});

第三个实际上有点复杂,我需要考虑如何进一步解决这个问题。我现在将回答,让您朝着正确的方向前进,并很快编辑和更新帖子以解决第三个问题。

关于php - Laravel Eloquent 困难关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44221365/

相关文章:

php - 显示子文件夹php文件中的php文件

php - MySQLI 在生产中发生 fatal error ,但在开发中则不然

mysql - 如何在 TomEE 管理的数据源连接上创建语句?

java - Hibernate 不使用 spring boot 从 mysql 表返回数据

laravel - 如何在 Laravel 中插入数据库之前连接自动增量值

php - 如何在laravel中生成自定义标识值?

php - 在 strpos() 的字符串中使用正则表达式

php - 将 jQuery 保存到数据库?

mysql - 如何在我的 Codeigniter 模型中使用 SQL LEFT JOIN

php - 如何从 Laravel 中抛出的异常中获取 HTTP 状态码?