Laravel 使用 Eloquent 的多对多关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32059809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:12:34  来源:igfitidea点击:

Laravel many to many relationship using Eloquent

phplaraveleloquentlaravel-5.1

提问by salep

I'm trying to create a many to many relationship using Laravel, but I am stuck.

我正在尝试使用 Laravel 创建多对多关系,但我被卡住了。

Here's my current table model:

这是我当前的表模型:

album

专辑

album_id
name
created_at

user_image

用户图像

user_image_id
value

albumxuser_image (junction table)

相册xuser_image(连接表)

albumxuser_image_id (primary key & auto increment)
album_id (FK from album)
user_image_id (FK from user_image)

I want to be able to get the album name from albumxuser_image table.

我希望能够从专辑 xuser_image 表中获取专辑名称。

Here's what I've done so far.

这是我到目前为止所做的。

Album.php model

相册.php模型

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Album extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'album';
    protected $primaryKey = 'album_id';

    public function AlbumxUserImage() {
        return $this->belongsToMany('AlbumxUserImage', 'albumxuser_image','album_id','user_image_id');
    }
}

routes.php (I didn't use view since I'm making a practice)

route.php(我没有使用视图,因为我正在练习)

Route::get('all', function() {
    $albumxuserimage = AlbumxUserImage::all();
    foreach ($albumxuserimage->AlbumxUserImage as $getthem) {
        echo $getthem->pivot->name; // I want to get the name column of the album table.
    }
});

AlbumxUserImage.php

相册xUserImage.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class AlbumxUserImage extends Model {

    protected $table = 'albumxuser_image';
    protected $primaryKey = 'albumxuser_image_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['album_id', 'user_image_id'];
}

Here's the error I get

这是我得到的错误

Call to undefined method Illuminate\Database\Eloquent\Collection::AlbumxUserImage()

回答by BrokenBinary

You're trying to call AlbumxUserImage()on a Collectionof models instead of on each individual model.

您正在尝试调用AlbumxUserImage()a Collectionof 模型而不是每个单独的模型。

AlbumxUserImage::all()is returning a Collectionof models, which you can think of as an array. You need to iterate over the collection and call AlbumxUserImage()on each model in the collection.

AlbumxUserImage::all()正在返回一个Collection模型,您可以将其视为一个数组。您需要遍历集合并调用集合中的AlbumxUserImage()每个模型。

That may solve your problem for now, but you seem to not understand how many-to-many relationshipswork in Laravel.

这可能暂时解决了您的问题,但您似乎不了解Laravel 中的多对多关系

How you should be doing Many-To-Many

你应该如何做多对多

I don't know why you have a model for your pivot table. That is not how Laravel normally handles models with many-to-many relationships. A typical many-to-many relationship with your tables would look like this:

我不知道为什么你的数据透视表有一个模型。这不是 Laravel 通常处理多对多关系模型的方式。与表的典型多对多关系如下所示:

Models:

楷模:

class Album extends Model {
    protected $table = 'album';
    protected $primaryKey = 'album_id';

    public function images() {
        return $this->belongsToMany('App\UserImage', 'albumxuser_image','album_id','user_image_id');
    }
}

class UserImage extends Model {
    protected $table = 'user_image';
    protected $primaryKey = 'user_image_id';

    public function albums() {
        return $this->belongsToMany('App\Album', 'albumxuser_image','user_image_id','album_id');
    }
}

Usage:

用法:

// Get all album names through UserImage
$userImages = UserImage::all();
foreach ($userImages as $userImage) {
    foreach ($userImage->albums as $album) {
        echo $album->name;
    }
}

// Get all images through Album
$albums = Album::all();
foreach ($albums as $album) {
    foreach ($album->images as $image) {
        echo $image->value;
    }
}