【问题标题】:Query first model based on parameters from child model in eloquent laravel在 eloquent laravel 中根据子模型的参数查询第一个模型
【发布时间】:2015-09-01 21:03:55
【问题描述】:

我有 2 个用户表,对应的 UserBUser 雄辩模型。我正在尝试查询User,并且仅根据BUser 上的参数返回结果。

我目前正在这样做:

public function scopeMarketplace($query) {
    return $query->with(['buser' => function($q) {
        $q->where('marketplace', '=', 1);
    }]);
}

返回所有Users 但仅包括BUser 如果marketplace = 1 但我不想返回任何Users,除非满足相应的BUser 参数。 SQL 最终是:

select * from `users` limit 50 offset
select * from `busers` where `busers`.`id` in ('62', '63', '99', '100', '101', '102', '104', '105', '106', '107', '108', '109', '110', '111', '113', '114', '115', '116', '117', '118', '126', '128', '130', '131', '132', '142', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '165', '166', '167', '168', '169', '170', '171', '172') and `marketplace` = '1'

这会获取所有User 对象,然后是查询的BUser - 因此返回错误的数据。

UserBUser 的关系是:

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasOne
 */
public function buser()
{
    return $this->hasOne('App\BUser', 'id', 'id');
}

【问题讨论】:

  • 两张表是什么关系?
  • @Bogdan 目前在 MySQL 中没有关系
  • 要根据另一个表的列值查询一个表的结果,它们之间应该有关系。
  • 好的,如果我添加一个外键来链接这两个表,Eloquent 会理解这一点并创建正确的查询?
  • 是的,如果 relationships 在 Eloquent 模型中被正确定义。

标签: laravel eloquent


【解决方案1】:

您正在寻找whereHas 方法:

public function scopeMarketplace($query) {
    $query->whereHas('buser', function ($q) {
        $q->where('marketplace', 1);
    });
}

【讨论】:

  • 这确实是我正在寻找的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
相关资源
最近更新 更多