Dev*_*Dev 5 php laravel laravel-5.2
我有两个表:users,orders.我试图获得当前用户的所有订单.
Users Orders
_____ ______
id | name id | user_id
Run Code Online (Sandbox Code Playgroud)
用户模型:
public function orders(){
return $this->hasMany("App\Order");
}
Run Code Online (Sandbox Code Playgroud)
订单型号:
public function user(){
return $this->hasOne("App\User", 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
在控制器中查询:
public function index()
{
$orders = Order::where('user_id', Auth::guard('api')->id())->get();
return response()->json(
$orders->user
);
}
Run Code Online (Sandbox Code Playgroud)
我得到NULL结果,我做错了,因为两个表中都有相关的行.
如果您想检索属于当前用户的所有订单,请尝试使用以下函数。
\npublic function index()\n{\n $orders = Auth::user()->with('Orders')->get()->toArray();//To get the output in array\n /* ^ ^\n This will get the user | This will get all the Orders related to the user*/\n \n return response()->json($orders);\n}\nRun Code Online (Sandbox Code Playgroud)\n正如 @Martin Heraleck\xc3\xbd 所指出的,您还需要hasOne()将belongsTo()in Order Model。请参阅以下内容(从 @Martin Heraleck\xc3\xbd 答案复制)
public function user(){\n return $this->belongsTo("App\\User");// second and third arguments are unnecessary.\n}\nRun Code Online (Sandbox Code Playgroud)\nhas_one和belongs_to通常在它们指向其他相关模型的意义上是相同的。belongs_to确保该模型已定义foreign_key。 has_one确保另一个模型已定义 has_foreign key。
你的$orders数组看起来像这样:
User => [\n id => 'user id',\n name => 'user name'\n orders => [\n 0 => [\n //order data\n ]\n 1 => [\n //order data\n ]\n .\n .\n .\n .\n ]\n]\nRun Code Online (Sandbox Code Playgroud)\n