【发布时间】: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 它确实缩短了过程。但并不是我真正想知道的