laravel雄辩的一对多关系

San*_*ila 1 php one-to-many relationships laravel eloquent

早上好,我在Eloquent的模型关系方面有点麻烦,我需要用中间表链接这些文章的文章和图像.在中间表中,我想添加文章和图像的ID,我想检索属于文章的所有图像,管理关系的最佳方法是什么?提前致谢

Ale*_*nin 6

您不需要使用数据透视表,因为它是一对多的关系.

只需使用hasMany()关系:

public function images()
{
    return $this->hasMany('App\Image');
}
Run Code Online (Sandbox Code Playgroud)

然后使用预先加载来加载所有带有文章的图像:

$article = Article::with('images')->where('id', $articleId)->first();
Run Code Online (Sandbox Code Playgroud)