[英]How to use where in laravel relationships?
I have a relationship
on Orders
and Customers
.我在
Orders
和Customers
上有relationship
。
a row from customers
table: customers
表中的一行:
customer_id![]() |
customer_name![]() |
customer_state![]() |
customer_city![]() |
---|---|---|---|
1 ![]() |
Amin![]() |
Yazd![]() |
Yazd![]() |
a row from orders
table: orders
表中的一行:
order_id ![]() |
customer_id![]() |
product_id ![]() |
factor_id![]() |
---|---|---|---|
1 ![]() |
1 ![]() |
3 ![]() |
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.