Php 使用关系表从数据库中获取记录时出现问题
我在使用中间表将照片与标签关联时遇到问题 在下面的示例中,如何使用Laravel中的雄辩关系方法选择属于标记1的所有照片 我有这些桌子:Php 使用关系表从数据库中获取记录时出现问题,php,mysql,laravel,eloquent,eloquent-relationship,Php,Mysql,Laravel,Eloquent,Eloquent Relationship,我在使用中间表将照片与标签关联时遇到问题 在下面的示例中,如何使用Laravel中的雄辩关系方法选择属于标记1的所有照片 我有这些桌子: -Photos Table | id | name | description | 1 photo1.png .... 2 photo2.png .... 3 photo3.png .... 首先,您需要确保照片和标签表都定义了关系 在照片模型下,您应该具有以下
-Photos Table
| id | name | description |
1 photo1.png ....
2 photo2.png ....
3 photo3.png ....
首先,您需要确保照片和标签表都定义了关系 在照片模型下,您应该具有以下功能:
public function tags() {
return $this->belongsToMany(
Tag::class,
"photos_tags", // the name of the pivot table
"photo_id",
"tag_id"
);
}
public function photos() {
return $this->belongsToMany(
Photo::class,
"tags_photos", // the name of the pivot table
"tag_id",
"photo_id"
);
}
在标记模型下,您应该具有以下功能:
public function tags() {
return $this->belongsToMany(
Tag::class,
"photos_tags", // the name of the pivot table
"photo_id",
"tag_id"
);
}
public function photos() {
return $this->belongsToMany(
Photo::class,
"tags_photos", // the name of the pivot table
"tag_id",
"photo_id"
);
}
现在,要访问与id 1照片相关的所有标签,您可以调用以下命令:
Photo::findOrFail(1)->tags()->get();
同样,你也可以为一个特定的标签获取所有的照片
Tag::findOrFail(1)->photos()->get();
希望这将引导您实现您的愿望。很高兴听到这个消息!祝你在未来的发展中好运^^