Laravel通过模型实例交往关系
在我的Laravel 9项目中,我的用户模型属于3个模型(分销商,代理商和广告商),例如:
public function distributor()
{
return $this->belongsTo(Distributor::class);
}
public function agency()
{
return $this->belongsTo(Agency::class);
}
public function advertiser()
{
return $this->belongsTo(Advertiser::class);
}
我使用此功能在我的Distributorrepository(以及其他2个模型的存储库)中关联:
public function associateUser($id, $user_id)
{
$user = $this->user->find($user_id);
$distributor = $this->find($id);
$result = $user->distributor()->associate($distributor)->save();
return $result;
}
现在,我想修改它们以将它们关联起来通过用户的ID和关系模型实例(分销商,代理商和广告商)在我的用户介绍(或用户服务)中动态上,例如:
public function associate($id, $modelInstance)
{
// Something happens here
}
这是可能的吗?谢谢!
In my Laravel 9 project, My User Model is belongs to 3 models (Distributor, Agency and Advertiser) like:
public function distributor()
{
return $this->belongsTo(Distributor::class);
}
public function agency()
{
return $this->belongsTo(Agency::class);
}
public function advertiser()
{
return $this->belongsTo(Advertiser::class);
}
And I use this function to associate in my DistributorRepository(and other 2 model's repositories):
public function associateUser($id, $user_id)
{
$user = $this->user->find($user_id);
$distributor = $this->find($id);
$result = $user->distributor()->associate($distributor)->save();
return $result;
}
Now, I want to modify to associate them by user's id and relation model instance (Distributor, Agency and Advertiser) in my UserRepository (or UserService) dynamically, like:
public function associate($id, $modelInstance)
{
// Something happens here
}
Is that possible and how to do? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确,那么您可以这样做:
您可以这样使用:
If I understand right, then you can do it with:
And you can use it like this: