簡體   English   中英

Laravel使用Eloquent進行多對多關系

[英]Laravel many to many relationship using Eloquent

我正在嘗試使用Laravel建立多對多關系,但我陷入了困境。

這是我當前的表格模型:

專輯

album_id
name
created_at

user_image

user_image_id
value

albumxuser_image(連接表)

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(自從我練習以來就​​沒有使用過view)

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

您正在嘗試在模型Collection上而不是在每個模型上調用AlbumxUserImage()

AlbumxUserImage::all()返回一個模型Collection ,您可以將其視為數組。 您需要遍歷集合並在集合中的每個模型上調用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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM