【问题标题】:How to select specific column from parent and child in laravel如何在laravel中从父子节点中选择特定列
【发布时间】:2022-11-04 00:05:34
【问题描述】:

请在下面查看我的代码。

控制器

$orders = Order::with('product:id,name')
    ->select([
            'id',
            'order_number',
            'ordered_on',
            'status',
            'total'
        ])
        ->where('customer_id', session('customer_id'))
    ->orderBy('ordered_on', 'DESC')
        ->paginate(6);
    dd($orders);

订购型号

public function product()
{
  return $this->belongsTo(Product::class);
}

当您检查product 关系数据时,上面的结果返回null

我需要的

Order 模型中选择特定列,然后从product 关系中选择特定列。

【问题讨论】:

  • ->select() 中你必须包含外键product_id
  • @ericmp 哇,有什么参考吗?它现在正在工作。
  • 我几乎没有试图找到这方面的文档,但找不到它,哈哈

标签: laravel eloquent


【解决方案1】:

您需要添加要引用的外键:

->select([
    'product_id'
    ...
])
...

文档:https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-specific-columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多