我有两个表:users
、orders
。我尝试获取当前用户的所有订单。
Users Orders
_____ ______
id | name id | user_id
用户模型:
public function orders(){
return $this->hasMany("App\Order");
}
订购型号:
public function user(){
return $this->hasOne("App\User", 'user_id', 'id');
}
在 Controller 中查询:
public function index()
{
$orders = Order::where('user_id', Auth::guard('api')->id())->get();
return response()->json(
$orders->user
);
}
我得到 NULL 结果,我做错了什么,因为两个表中都有相关行。
最佳答案
如果要检索属于当前用户的所有订单,请尝试使用以下函数。
public function index()
{
$orders = Auth::user()->with('Orders')->get()->toArray();//To get the output in array
/* ^ ^
This will get the user | This will get all the Orders related to the user*/
return response()->json($orders);
}
正如@Martin Heralecký 所指出的,您还需要将订单模型中的 hasOne()
更改为 belongsTo()
。请参阅以下内容(复制自@Martin Heralecký 回答)
public function user(){
return $this->belongsTo("App\User");// second and third arguments are unnecessary.
}
为什么 belongsTo():
has_one
和 belongs_to
在指向其他相关模型的意义上通常是相同的。 belongs_to
确保此模型定义了 foreign_key。 has_one
确保另一个模型已定义外键。
您的 $orders
数组将如下所示:
User => [
id => 'user id',
name => 'user name'
orders => [
0 => [
//order data
]
1 => [
//order data
]
.
.
.
.
]
]
关于php - 如何从 Laravel 中的相关表中获取数据(一对多)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446355/