使用Eloquent实现Laravel的多对多关系

4
我正在尝试使用Laravel创建多对多关系,但我卡住了。
这是我的当前表模型:
相册(album)
album_id
name
created_at

用户图像

user_image_id
value

相册用户图片(连接表)

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

我想从albumxuser_image表中获取专辑名称。
目前我已经做了以下工作。
Album.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(我没有使用视图,因为我正在练习)
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

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'];
}

这是我得到的错误信息。
Call to undefined method Illuminate\Database\Eloquent\Collection::AlbumxUserImage()

你有一个 AlbumxUserImage 模型吗?我们能看一下吗? - BrokenBinary
为什么不直接从“Album”模型中获取专辑名称呢?为什么要先查找枢轴表呢? - BrokenBinary
1个回答

11

你正在尝试在模型的集合上调用AlbumxUserImage()而不是在每个单独的模型上调用。

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

这可能暂时解决了你的问题,但你似乎不理解Laravel中的多对多关系是如何工作的。

应该如何处理多对多关系

我不知道为什么你要为你的中间表创建一个模型,这不是Laravel通常处理具有多对多关系的模型的方式。使用你的表进行典型的多对多关系,看起来应该像这样:

模型:

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');
    }
}

用法:

// 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;
    }
}

非常感谢。在我提问之前,我已经阅读了文档,但是我并没有完全理解。现在我想我明白了,谢谢。 - salep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接