【问题标题】:Laravel Eloquent - where relationship field does not equalLaravel Eloquent - 关系字段不等于
【发布时间】:2020-09-23 12:34:32
【问题描述】:

我认为这会很简单,但目前还没有打球。

我有 2 个表来回答这个问题,“applications”和“application_call_logs”。

此查询需要从应用程序表中返回所有最新调用日志的状态不为 X。

这是当前查询:

$query = Application::query();

$query->where(function($query) {
    $query->whereDoesntHave('call_logs');
    $query->orWhereHas('latest_call_log', function($q) {
        $q->where('status', '!=', 'not interested');
    });
});

return $query->get();

这应该返回所有没有呼叫日志的行,或者最新的呼叫日志没有等于特定字符串的状态字段。

这里是:

$q->where('status', '!=', 'not interested');

如果 call_logs 有超过 1 行,似乎没有影响,即使我正在查询最新的关系。我还验证了 latest 正在返回正确的最新记录。

Application 模型中的两种关系是:

public function call_logs()
{
    return $this->hasMany('App\ApplicationCallLog', 'lead_id', 'id');
}

public function latest_call_log()
{
    return $this->hasOne('App\ApplicationCallLog', 'lead_id', 'id')->latest();
}

检查生成的 SQL:

select * from `applications` where (not exists (select * from `lead_call_logs` where `applications`.`id` = `lead_call_logs`.`lead_id`) or exists (select * from `lead_call_logs` where `applications`.`id` = `lead_call_logs`.`lead_id` and `status` != ?))

【问题讨论】:

  • 检查生成的 SQL 或许是个好主意?
  • @onlineThomas 好声音,刚刚更新了问题,我也看了一下。

标签: sql laravel eloquent


【解决方案1】:

有一个解决方案应该适合这种情况:

我认为这一行有代码的星期点:

return $this->hasOne('App\ApplicationCallLog', 'lead_id', 'id')->latest();

这应该是 hasMany,但您使用 hasOne 将结果限制为一个。

如果你尝试过:

 return $this->hasMany('App\ApplicationCallLog', 'lead_id', 'id')->latest()->limit(1);

它根本行不通,因为所有结果的结果都将限制在 ApplicationCallLog 中......

会,有一个包 staudenmeir/eloquent-eager-limit 是专门针对这种情况制作的:

composer require staudenmeir/eloquent-eager-limit:"^1.0"

class Application extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
public function latest_call_log()
{
    return $this->hasMany('App\ApplicationCallLog', 'lead_id', 'id')->latest()
->limit(1);
}

}

class ApplicationCallLog extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

使用此包将限制 ApplicationCallLog 用于查询中的每个结果,而不是所有结果,这对 hasOne 具有相同的效果 ....

我认为有了这个小改进:

$q->where('status', '!=', 'not interested');

会起作用...

更多关于 eloquent-eager-limit 包的信息:

https://github.com/staudenmeir/eloquent-eager-limit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2019-03-04
    • 2018-06-19
    • 2023-03-28
    • 1970-01-01
    • 2018-10-22
    • 2017-07-18
    • 2016-08-13
    相关资源
    最近更新 更多