HasMany关联时怎么多字段关联?
例子,我的主表post对应多个资源contents, 这样写没问题
public function contents(): HasMany
{
return $this->hasMany(Content::class, 'post_id', 'post_id');
}
甚至我还可以带条件
public function contents(): HasMany
{
return $this->hasMany(Content::class, 'post_id', 'post_id')->where('status', 'active');
}
但是,我的A可以反复修改,并且我要记录每个修改的版本,于是post与contents表加上了version_id,每次修改自增,contents只增加不修改删除,按post表的version_id对应即可
我尝试这样做
public function contents(): HasMany
{
return $this->hasMany(Content::class, 'post_id', 'post_id')->where('version_id', $this->version_id);
}
发现version_id是null的
// 这样写没问题,但是因为还没有查询出数据,不知道version_id是多少
$post = Post::with(['publisher', 'contents'=>function($query){
$query->where('version_id', 16);
}])->where('post_id', $post_id)->first();
只能手动另外查吗, 还是有什么好办法可以使用laravel自带的关联
还有个办法, 但需要再写一行
$post->contents()->where('version_id', $post->version_id)->get();
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: