Laravel Eloquent关联模型whereHas条件不生效问题求助
Hey there, let's figure out why your whereHas constraint isn't working as expected. The root cause here lies in how you've defined the many-to-many relationship in your Order model—let's break this down step by step:
1. First, fix the belongsToMany relationship definition
Laravel's belongsToMany method has a strict parameter order that you've mixed up. The correct format is:
return $this->belongsToMany(关联模型类, 中间表名称, 当前模型在中间表的外键, 关联模型在中间表的外键);
Your current code uses the orders table (the main table for your Order model) as the pivot table for the many-to-many relationship, which is incorrect. Many-to-many associations require a separate pivot table (like order_order_carpets, following Laravel's naming conventions) to link the two models.
Corrected Order Model Code
class Order extends Model { protected $table = 'orders'; // Fixed many-to-many relationship public function order_carpets() { // Replace 'order_order_carpets' with your actual pivot table name // Make sure the pivot table has `order_id` (from orders table) and `carpet_id` (from order_carpets table) return $this->belongsToMany(Order_carpet::class, 'order_order_carpets', 'order_id', 'carpet_id'); } public function customers() { // You'll need to fix this relationship too using the same logic, e.g.: // return $this->belongsToMany(Customer::class, 'order_customers', 'order_id', 'customer_id'); } }
2. Verify your whereHas query
Once you fix the relationship definition, your original query should start working correctly:
$orders = Order::whereHas('order_carpets', function($q){ $q->where('carpent_no', '1345'); })->get();
Quick additional checks
- Double-check that your pivot table exists and has the correct foreign key fields (like
order_idandcarpet_id) - Confirm the field name
carpent_nois spelled correctly (might be a typo forcarpet_no?) - Ensure your
Order_carpetmodel has the correct table and field configurations
内容的提问来源于stack exchange,提问作者BalG Lal Shrestha

