简体   繁体   English

如何在 laravel 关系中使用 where?

[英]How to use where in laravel relationships?

I have a relationship on Orders and Customers .我在OrdersCustomers上有relationship
a row from customers table: customers表中的一行:

customer_id客户ID customer_name顾客姓名 customer_state客户状态 customer_city客户城市
1 1 Amin阿明 Yazd亚兹德 Yazd亚兹德

a row from orders table: orders表中的一行:

order_id order_id customer_id客户ID product_id product_id factor_id因子_id
1 1 1 1 3 3 4 4

Now I want order rows where customer_state is yazd.现在我想要customer_state是 yazd 的订单行。

Order.php订购.php

public function customer()
{
    return $this->belongsToMany(Customer::class, 'orders', 'order_id', 'customer_id');
}

OrdersController.php订单控制器.php

$state = "Yazd";
$reportItem = Order::whereHas("customer", function ($query) use ($state) {
    $query->where('customer_state', $state)->get();
});

It doesn't work.它不起作用。 How I can handle this?我该如何处理?

You have put get() at the wrong place.你把get()放在了错误的地方。

Change this改变这个

$reportItem = Order::whereHas("customer", function ($query) use ($state) {
    $query->where('customer_state', $state)->get();
});

To

$reportItem = Order::whereHas("customer", function ($query) use ($state) {
    $query->where('customer_state', $state);
})->get();

Learn more about laravel relations了解有关laravel 关系的更多信息

What I understand from the given input you're not using the proper relation here: The belongsToMany relation is used for many-to-many relations using an allocation table.我从给定的输入中了解到您在这里没有使用正确的关系: belongsToMany关系用于使用分配表的多对多关系。 But you are actually using a one-to-many relation => one customer can have many orders.但您实际上使用的是一对多关系 => 一个客户可以有多个订单。 In this case you should use a belongsTo relation on Order Model or/and a hasMany relation on Customer Model:在这种情况下,您应该使用 Order Model 上的belongsTo关系或/和客户 Model 上的hasMany关系:

// Order.php

public function customer() {
    return $this->belongsTo(Customer::class)
}

// Customer.php

public function orders() {
    return $this->hasMany(Order::class)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM