【问题标题】:Problem when getting records from database with relationship table使用关系表从数据库中获取记录时出现问题
【发布时间】:2020-05-15 03:28:45
【问题描述】:

我无法使用中间表将照片与标签关联起来。

在下面的示例中,如何在 Laravel 中使用 Eloquent 关系方法选择属于标签 1 的所有照片?

我有这些表:

-Photos Table

 |  id  |    name    | description |
    1     photo1.png      ....
    2     photo2.png      ....
    3     photo3.png      ....
-Tags Table

 |  id  |    name    |
    1      Aesthetic
    2        Dark
-Tags Relations

 | id | tag_id | photo_id |
   1      1         3
   2      1         2
   3      2         1

【问题讨论】:

    标签: php mysql laravel eloquent eloquent-relationship


    【解决方案1】:

    首先,您需要确保 Photos 和 Tags 表都定义了关系。

    在照片模型下你应该有以下功能:

    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();
    

    希望这会引导您实现您的愿望。

    【讨论】:

    • 很高兴听到这个消息!祝你进一步发展好运!^^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2020-01-26
    • 1970-01-01
    • 2021-12-21
    • 2016-01-29
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多