【问题标题】:Multiple foreign keys in hasMany relationship causing troubles with extra where clausehasMany 关系中的多个外键导致额外的 where 子句出现问题
【发布时间】:2015-03-18 22:33:46
【问题描述】:

假设您有一个团队和一个比赛桌。该团队有多个匹配项,外键位于visitant_id 或local_id(另请参见https://github.com/laravel/framework/issues/1272

在团队模型中:

public function allMatches()
{
     return $this->hasMany('Match', 'visitant_id')->orWhere('local_id', $this->id);
}

这样可以正常工作:

$team = Team::find(2);
$matches = $team->all_matches;

此查询的结果:

 select *
 from `matches` 
 where `matches`.`visitant_id` = ? 
 or `local_id` = ?

但是,当使用额外的 where 子句进行扩展时,例如:

$matches = $team->all_matches->where('type','=',1);

查询变为

 select * 
 from `matches` 
 where `matches`.`visitant_id` = ? 
 or `local_id` = ? and 'type' = ?

这意味着它会选择所有访问者匹配项,即使类型不正确,因为该子句周围没有 ()。有什么办法解决吗?

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    您可以使用参数分组。这里有描述http://laravel.com/docs/4.2/queries#advanced-wheres

    【讨论】:

    • 怎么做?第一个 where 是在关系中创建的,你不能只在闭包中弹出它......
    • 这不适用于我的问题案例,因为要么我使用高级查询并且它不再返回关系,要么就像@lukasgeiter 说关闭必须在关系内部,这是我不想要的。
    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多