Eloquent: 如果不存在则创建关系
Eloquent: Create relation if not exist
订阅 table:id,client_id,状态,valid_until
客户表: id, name
型号Client.php:
public function subscription {
return $this->hasOne(Subscription::class)
}
我想使用 $client->subscription->start()
来:
- 如果之前的关系已经存在:
status=1, valid_until \now()+addDays(30)
- 如果关系不存在,则使用上述数据创建订阅行。
可能吗?
或者我是否必须在 subscription.php 中构建一个静态函数。例如:Subscription::start($client)
谢谢
我认为你需要像 https://laravel.com/docs/7.x/eloquent-relationships#default-models 这样的东西来适应你的要求。
订阅 table:id,client_id,状态,valid_until 客户表: id, name
型号Client.php:
public function subscription {
return $this->hasOne(Subscription::class)
}
我想使用 $client->subscription->start()
来:
- 如果之前的关系已经存在:
status=1, valid_until \now()+addDays(30)
- 如果关系不存在,则使用上述数据创建订阅行。
可能吗?
或者我是否必须在 subscription.php 中构建一个静态函数。例如:Subscription::start($client)
谢谢
我认为你需要像 https://laravel.com/docs/7.x/eloquent-relationships#default-models 这样的东西来适应你的要求。