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();
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.
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.
In Eloquent, you can delete database records conveniently with the delete method from the parent Model class.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With