Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent With() With()

How do I go about using multiple Eloquent With()'s?

PortalPlaylistElement Model

class PortalPlaylistElement extends Model
{
    public $primaryKey = 'code';
    public $incrementing = false;
    public $timestamps = false;

    public function AirtimePlaylists()
    {
        return $this->hasOne('App\AirtimePlaylist','id','playlist_id');
    }
}

AirtimePlaylistContent Model

class AirtimePlaylistContent extends Model
{
    protected $table = 'cc_playlistcontents';
}

AirtimePlaylistModel

class AirtimePlaylist extends Model
{
    protected $table = 'cc_playlist';

    public function PortalPlaylistElements()
    {
        return $this->belongsTo('App\PortalPlaylistElement','playlist_id');
    }

    public function AirtimePlaylistContents()
    {
        return $this->hasMany('App\AirtimePlaylistContent','playlist_id');
    }
}

I have no problems with:

AirtimePlaylist::with('AirtimePlaylistContents')->get());

or

PortalPlaylistElement::with('AirtimePlaylists')->get();

But I'd like to get all AirtimePlaylistContents, in an AirtimePlaylist that belongs to a PortalPlaylistElement.

In essence, (Pseudo code)

PortalPlaylistElement::with('AirtimePlaylists')::with('AirtimePlaylistContents')->get();
like image 296
Scott Robinson Avatar asked Jun 01 '16 18:06

Scott Robinson


People also ask

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What does get () do in Laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What is the purpose of the eloquent delete () method?

In Eloquent, you can delete database records conveniently with the delete method from the parent Model class.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


1 Answers

nested relations

 with('relation1.relation2.relation3')->get(); // relation1 has relation2 relation2 has relation 3

not nested relations

 with('relation1','relation2','relation3')->get(); // you model has all relations
like image 138
Achraf Khouadja Avatar answered Sep 25 '22 02:09

Achraf Khouadja