Laravel many to many relationship using Eloquent

前端 未结 1 1301
挽巷
挽巷 2020-12-10 19:57

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

Here\'s my current table model:

album

album_id
name
created_         


        
相关标签:
1条回答
  • 2020-12-10 20:07

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

    AlbumxUserImage::all() is returning a Collection of 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.

    That may solve your problem for now, but you seem to not understand how many-to-many relationships work in 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:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题