gpt4 book ai didi

mysql - Laravel 三个模型之间的关系

转载 作者:行者123 更新时间:2023-11-29 09:34:47 24 4
gpt4 key购买 nike

sold_items:
id order_id customer_id name
-- -------- ----------- ----
1 5 14 An object

orders:
id po_num
-- ------
... ...
5 123


customers:
id name
-- ----
... ...
14 John Doe

一个SoldItem有一个 order_id和一个 customer_id .

我正在尝试定义一个 hasOne Order 之间的关系及其 Customer通过SoldItem无需插入customer_id Order 中的列模型表。

<强> hasOneThrough 似乎是解决方案,但我不知道从哪里开始,或者这就是答案吗?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
public $timestamps = false;
protected $guarded = ['id'];

public function sold_items()
{
return $this->hasMany('App\SoldItem');
}

public function customer()
{
// return $this->hasOneThrough();
}
}

最佳答案

针对客户模型

{

public function sold_items()
{
return $this->hasMany('App\SoldItem');
}


}

对于订单模型

{

public function sold_items()
{
return $this->hasOne('App\SoldItem');
}


}

对于已售商品模型

{

public function customer()
{
return $this->belongsto('App\Cutomer');
}

public function order()
{
return $this->belongsto('App\Order');
}

}

我更喜欢先处理它们的关系,然后使用 with() 函数来获取它们的值。

use App\Customer;

$customer = Customer::with('sold_items','sold_items.order')->get();

关于mysql - Laravel 三个模型之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com