如果要检索属于当前用户的所有订单,请尝试使用以下功能.
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);
}
正如@MartinHeralecký所指出的,您还需要在订单模型中将hasOne()更改为belongsTo().请参阅以下内容(复制自@MartinHeralecký答案)
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确保定义了另一个模型has_foreign键.
你的$orders数组看起来像这样:
User => [
id => 'user id',
name => 'user name'
orders => [
0 => [
//order data
]
1 => [
//order data
]
.
.
.
.
]
]