spoon
4 years ago

Many to many relationships with Eloquent

Posted 4 years ago by spoon

Hello!

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_at

user_image
user_image_id
value

albumxuser_image (junction table)
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 album table using this relationship.

Album.php model


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

UserImage.php model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class UserImage extends Model {

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

    protected $fillable = ['value', 'type', 'size', 'importance', 'date'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */

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

}

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

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

    $albumxuserimage = AlbumxUserImage::all();
    foreach ($albumxuserimage->AlbumxUserImage as $getthem) {
        echo $getthem->pivot->name; // I want to get the name column of the album table so I won't be dealing with bunch of joins, but it doesn't work. What's the proper way to do this?
    }
});

Please sign in or create an account to participate in this conversation.