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

标签 php laravel laravel-5.2

我有两个表: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');
}

在 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_onebelongs_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/

相关文章:

PHP INSERT 由于某些未知原因无法正常工作

php - 如何在单个查询中获取帖子标题、描述和图像

php - MySQL 查询 CASE 或 JOIN 或 UNION - 使用哪个?

php - 验证表单中公开的主键/外键是否完好无损

php - 未出现 Laravel 5.2 验证错误

php - 通过日期按年份搜索(仅 'date' ,不是时间戳或其他),PHP 通过从变量传递

php - Laravel 中的依赖注入(inject)

php - Laravel Queue with Supervisor,运行但不处理作业

laravel - 重命名 Laravel 5 中的索引

php - 从存储文件夹下载的 Laravel 文件损坏