【问题标题】:how to use laravel eloquent to get and display data from other tables如何使用 laravel eloquent 从其他表中获取和显示数据
【发布时间】:2019-08-18 19:35:20
【问题描述】:

我在我的控制器中使用这些代码从我的 2 个表中获取所有数据,它工作正常

$All = Customers::with('order')->paginate(10);

return response()->json([
    'code' => 0,
    'success' => true,
    'data' => $All
], 200);

这是我如何定义这两个表之间的关系

class Customers extends Model
{
    public function order()
    {
        return $this->hasMany(Orders::class, 'customer_id', 'id');
    }
}

class Orders extends Model
{
    public function customers()
    {
        return $this->belongsTo(Customers::class, 'customer_id', 'id');
    }
}

现在我希望的输出是隐藏订单 ID、订单时间戳并将 customer_id 更改为客户姓名(客户姓名不在我的订单数据库表中)。

我在控制器中使用'data' => DataResource::collection($All),这是我的DataResource

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'order' => $this->order
    ];
}

当然输出与上图相同。

我的数据库结构:

  • 订单表:
  • 客户表:

谁能帮我解决这个问题?

【问题讨论】:

  • 以后,请直接在问题文本中添加与问题相关的所有数据。随着时间的推移,第三方页面和图片的链接可能会失效,导致问题变得毫无用处,因为无法再验证答案。
  • @Namoshek 我在发布问题时尝试发布图像,但不允许我将图像放入问题中,所以我别无选择放置链接。但不知何故现在它的作品
  • 嵌入图片并不能解决链接失效的问题。如果 imgur 几个月后删除了这些图片怎么办?如果没有图片中的信息,您的问题和可能的答案将没有多大意义。
  • @Namoshek 你能帮我解决这个问题吗? stackoverflow.com/questions/57545597/…

标签: php mysql laravel eloquent


【解决方案1】:

答案很简单,基本上是a copy of the official documentation。您只需要将您的订单也包含在OrderResource 中。

// DataResource
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'order' => OrderResource::collection($this->order)
    ];
}

// OrderResource
public function toArray($request)
{
    return [
        'items' => $this->items,
        'quantity' => $this->quantity
    ];
}

我真的不明白为什么您要在订单中包含customer_name,因为它已经存在于上面一个层次结构的客户对象中。但是如果你真的想添加它,你应该可以这样做:'customer_name' => $this->customers->name

附带说明:您确实应该与您的命名更加一致。为什么资源叫DataResource,而它大约是Customers?为什么您的模型以复数形式称为 Customers 而不是单数形式的 Customer,这是惯例(如果您认为一个模型代表一个客户,则更合乎逻辑)。为什么您的belongsTo 关系在返回一个客户时称为customers() 的复数形式,而您的hasMany 关系在返回一个或多个订单时称为order

【讨论】:

  • 感谢您的回答和建议,我会注意的。但是我还有一个问题要问您,我可以知道 ''customer_name' => $this->customers->name 客户指的是什么吗?
  • 指的是OrderResource中的数组,就是你要返回的地方。
  • 不,我的意思是,它是指我的 customers 表名还是 public function customers() (在我的 Orders 模型中)还是别的什么?
  • 指的是customers()函数。 Laravel 允许通过与关系方法同名的属性动态访问关系。因此,您可以使用$order->customers->name,而不是$order->customers()->getResults()->name
  • 但是 $this->customers->name$this->Customers->name 是如何工作的呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2015-09-05
  • 2016-09-09
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多