定义关系时更改模型的主键

时间:2017-06-07 06:47:19

标签: php orm laravel-5.3

在laravel关系中,我怎么能在飞行中更改模型主键? 像

/** table structures
* model1
* -- id (primary_key)
* -- uid (i just used this as an identifier to another model)
* model2
* -- id (primary_key)
*  -- uid (i just used this as an identifier to another model)
* model1_model2
* -- id
* -- model1_id (uid of model1)
* -- model2_id (uid of model2)
**/
// in Model1.php
public function relation()
{
  return $this->belongsToMany(Model2::class, 'model1_model2', 'mode1_id', 'mode2_id');
}
问题是。如何在调用Model1::relation() ?? ..

时更改Model1主键

1 个答案:

答案 0 :(得分:1)

很抱歉推送这篇旧帖子。但最近我遇到了同样的问题,发现这篇文章。

所以我做了一些研究,发现自5.5版Laravels belongsToMany方法支持$parentKey$relatedKey变量作为第五和第六参数。 https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_belongsToMany