Laravel - 有很多通过

时间:2016-10-04 10:13:21

标签: php mysql laravel

我正在尝试使用Laravel 5.3的Has Many Through option

编写数据库查询

我的数据库表格如下:

http://sqlfiddle.com/#!9/a9c9af

表格是:

公司 company_offers 报价

在我的模型中,我有以下设置:

public function offers()
    {
        return $this->hasManyThrough(
            'App\Offers', 'App\CompanyOffers',
            'company_offer_id', 'offer_id'
        );
    }

当我尝试运行以下代码行时:

return $this->whereHas('offers', function($query) use ($offer_id)
        {
            return $query->whereIn('offer_id', $offer_id);
        });

我收到错误:

  

完整性约束违规:1052 where子句中的'offer_id'列   含糊不清

如何纠正这种情况并使关系正确?

我需要获得优惠标题&为我的前端视图提供图标

希望这是有道理的,有人可以帮助我。

由于

1 个答案:

答案 0 :(得分:0)

"列' offer_id'在where where子句中含糊不清"基本上意味着SQL查询正在处理几个表,并且它不知道哪个表offer_id指的是:

例如,查询可能正在执行类似

的操作
select offers.* from offers
left join another_table on another_table.field = offers.field
where offer_id = ?

请注意,上表中的offer_id可以引用offersanother_table中的列。

纠正错误应采取的措施是在offer_id前加一个表名。像这样:

return $this->whereHas('offers', function($query) use ($offer_id) {
    return $query->whereIn('other_table.offer_id', $offer_id);
});