如何从Laravel中的相关表中获取数据(一对多)?

问题描述 投票:5回答:3

我有两张桌子:usersorders。我试图获得当前用户的所有订单。

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');
}

在控制器中查询:

public function index()
{

    $orders = Order::where('user_id', Auth::guard('api')->id())->get();
    return response()->json(
        $orders->user
    );
}

我得到NULL结果,我做错了,因为两个表中都有相关的行。

php laravel laravel-5.2
3个回答
2
投票

如果要检索属于当前用户的所有订单,请尝试使用以下功能。

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.
}

Why belongsTo():

has_onebelongs_to在某种意义上通常是相同的,它们指向其他相关模型。 belongs_to确保此模型定义了foreign_key。 has_one确保定义了另一个模型has_foreign键。

你的$orders数组看起来像这样:

User => [
 id => 'user id',
 name => 'user name'
 orders => [
  0 => [
         //order data
       ]
  1 => [
         //order data
       ]
       .
       .
       .
       .
   ]
]

2
投票

在Order模型中,您需要使用belongsTo关系:

public function user()
{
    return $this->belongsTo("App\User"); // second and third arguments are unnecessary.
}

1
投票

在用户模型中,您可以使用hasMany关系,例如:

App/User.php

public function orders()
{
   return $this->hasMany("App\Order", "user_id", "id");
}

现在你可以使用这个:

return User::find(1)->orders;
© www.soinside.com 2019 - 2024. All rights reserved.