【问题标题】:Eloquent::where() condition is not working as expected, but Collection::where() does workEloquent::where() 条件未按预期工作,但 Collection::where() 确实有效
【发布时间】:2021-08-30 22:49:19
【问题描述】:

我一直在使用 Eloquent,但我遇到了 Eloquent::where() 没有按预期工作的情况。不过,我设法让 Collection::where() 工作。但是,我仍然想知道为什么 Eloquent::where() 在我的情况下不起作用。我会尽量让问题简单,就这样吧:

  • 我的 Product 和 ProductCategory 是多对多关系,数据透视表名称是“product_relate_category”。
  • 这是它们之间的关系。它仍在工作,因此您可以跳过

Models/Product {
    public function productCategory() {
        return $this->belongsToMany(ProductCategory::class, 'product_relate_category','product_id','category_id');
    }
}
Models/ProductCategory {
    public function product() {
        return $this->belongsToMany(Product::class, 'product_relate_category', 'category_id', 'product_id');
    }
}

  • 这里是棘手的部分:我们需要展示相关产品,它们属于同一产品类别但具有不同的 ID。我们以第一个产品为例,任务是获取所有相关产品

    foreach (Product::first()->productCategory()->get() as $category)
    {
        foreach($category->product()->where("id", "<>", Product::first()->id)->get() as $result)
        {
             echo($result->name); 
        }
    }
    
  • 看起来像工作?不,它说:“违反完整性约束:where 子句中的 1052 列 'id' 不明确”。

  • 现在,如果我省略上面的 Eloquent::where() 条件,我可以访问所有带有“id”的产品,这是一个很大的混乱。

  • 但是,如果我将其更改为以下任何一种,它都可以正常工作

     $category->product()->where("product_id", "<>", Product::first()->id)->get()
    

    //通知“id”已更改为“product_id”

    $category->product()->get()->where("id", "<>", Product::first()->id) 
//Method order changed
  • 在第二个实例中,Collection::where() 已被调用,我非常不愿意使用它。那么对于这种情况以及为什么 Eloquent 会有这种行为方式有什么解释吗?

【问题讨论】:

  • 我猜实际上不需要那么多逻辑。你可以这样做 Product::with('productCategory')->get();
  • 这可能表明枢轴 product_relate_category 错误地有一个 id 字段
  • @JohnLobo 它确实缩短了过程。但并不是我真正想知道的

标签: php laravel eloquent orm


【解决方案1】:

在查询的 where 中,您使用了 product_relate_category 表和 products 表中存在的列“id”,因此数据库无法准确确定您的意思是什么列... 在这种情况下,您应该写出完整的列名:

 $category->product()->where("products.id", "<>", Product::first()->id)->get();

【讨论】:

  • 这绝对是问题所在。有没有关于该语法的文档?我想当使用 ->product() 时,Eloquent 会自动假设 products 表中的“id”列,它没有?
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多