简体   繁体   English

Laravel - 多对多关系

[英]Laravel - Many to Many relationship

I have 2 tables, users and pictures .我有 2 个表,用户图片 The tables have a many-to-many relationship and I have created a pivot table name user_pictures .这些表具有多对多关系,我创建了一个名为user_pictures的数据透视表。

The users table is as follows:用户表如下:

id
firstname
lastname

The pictures table is as follows:图片表如下:

id
filename
url 

The user_pictures table contains: user_pictures 表包含:

id
user_id
picture_id

When a user adds a picture, the picture filename and url is stored in the pictures table, and in the user_pictures table the picture_id of that picture is stored alongside the user_id of that user.当用户添加图片时,图片文件名url存储在图片表中,而在user_pictures表中,该图片的picture_id与该用户的user_id一起存储。

How can I retrieve all the picture filename and url related to the user that have added them using Eloquent ORM?如何使用 Eloquent ORM 检索与添加它们的用户相关的所有图片文件名url

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    // Define pictures with a pivot table link
    public function pictures() {
        return $this->belongsToMany('App\Models\UserPicture', 'user_pictures', 'picture_id', 'user_id');
    }
    //add methods
}

class UserPicture extends Model
{
    protected $table = 'user_pictures';
    public function picture() {
        return $this->hasOne('App\Models\Picture', 'id', 'picture_id');
    }

    public function user() {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }
    //add methods
}

class Pictures extends Model
{
    protected $table = 'pictures';
    //add methods
}

If you don't want to add timestamps to the tables you must add these 2 methods:如果您不想向表中添加时间戳,则必须添加以下 2 种方法:

 public function setCreatedAt($value) {
        // to disable created_at
    }

    public function setUpdatedAt($value) {
        // to disable created_at
    }

To fetch pictures from a user do this:要从用户那里获取图片,请执行以下操作:

$userPictures = UserPicture::where(array('user_id'=>1)->get();
foreach($userPictures as $userpicture) {
    $picture = $userpicture->picture();
}

In your User model add the following relation在您的User模型中添加以下关系

public function pictures() 
{
    return $this->belongsToMany(App\Picture::class, 'user_pictures');
}

In your Picture model add the follwing relation在您的Picture模型中添加以下关系

public function users()
{
    return $this->belongsToMany(App\User::class, 'user_pictures');
}

Then to get all pictures associated with a user然后获取与用户关联的所有图片

$pictures = $someUserObject->pictures;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM