gpt4 book ai didi

php - Laravel - 设置关系模型的默认值

转载 作者:行者123 更新时间:2023-12-02 04:26:54 25 4
gpt4 key购买 nike

我有一个表帐户:

act_id,
act_name,
act_address

我有一个表地址:

add_id,
add_street1,
<other fields you'd expect in an address table>

accounts.act_address 是addresses.add_id 的外键。在 Laravel 中,我有我的帐户模型:

use LaravelBook\Ardent\Ardent;
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Account extends Ardent
{
use SoftDeletingTrait;

protected $table = 'accounts';

protected $primaryKey = 'act_id';

public static $rules = array
(
'act_name' => 'required|unique:accounts'
);

protected $fillable = array
(
'act_name'
);

public function address()
{
return $this->hasOne('Address', 'add_id', 'act_address');
}
}

如您所见,我在这里设置了一对一关系。 (当然,Address 模型也有一个“belongsTo”)。这一切都有效。

问题是,地址外键可以为空,因为帐户不需要地址。因此,如果我在没有帐户->地址的情况下尝试访问它,我会收到“尝试访问非对象的属性”错误。

如果帐户记录没有设置,我想做的是将帐户->地址设置为新的地址对象(所有字段为空)。

我能够做的是在模型中创建第二种方法:

public function getAddress()
{
return empty($this->address) ? new Address() : $this->address;
}

或者,即时添加:

if (empty($account->address))
$account->address = new Address();

第一个解决方案非常接近,但我真的很想保留访问地址作为属性而不是方法的功能。

所以,我的问题是:
如果帐户->地址为空/为空,如何让帐户->地址返回新地址()?

哦,我尝试像这样覆盖 $attributes:

protected $attributes = array
(
'address' => new Address()
);

但这会引发错误。

最佳答案

使用访问器:

编辑:由于它是 belongsTo 而不是 hasOne 关系,所以有点棘手 - 你不能将模型与不存在的模型关联起来,因为后者没有 id:

public function getAddressAttribute()
{
if ( ! array_key_exists('address', $this->relations)) $this->load('address');

$address = ($this->getRelation('address')) ?: $this->getNewAddress();

return $address;
}

protected function getNewAddress()
{
$address = $this->address()->getRelated();

$this->setRelation('address', $address);

return $address;
}

但是,现在您需要这个:

$account->address->save();
$account->address()->associate($account->address);

这不是很方便。您也可以在 getNewAddress 方法中保存新实例化的地址,或重写 Account save 方法,以自动进行关联。无论如何,对于这种关系,我不确定这样做是否有意义。对于 hasOne 来说,它会发挥很好的作用。


下面是 hasOne 关系的样子:

public function getAddressAttribute()
{
if ( ! array_key_exists('address', $this->relations)) $this->load('address');

$address = ($this->getRelation('address')) ?: $this->getNewAddress();

return $address;
}

protected function getNewAddress()
{
$address = $this->address()->getRelated();

$this->associateNewAddress($address);

return $address;
}

protected function associateNewAddress($address)
{
$foreignKey = $this->address()->getPlainForeignKey();

$address->{$foreignKey} = $this->getKey();

$this->setRelation('address', $address);
}

您可以在单个访问器中完成所有这些操作,但这就是它“应该”的样子。

关于php - Laravel - 设置关系模型的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26302764/

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