Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Relationship Sub-Relationship?

I have an Offer class with the following relationship:

class Offer extends Model
{
    public function releases()
    {
        return $this->belongsToMany('App\Release');
    }
}

The Release class has this relationship:

class Release extends Model
{
    public function artist()
    {
        return $this->belongsTo('App\Artist');
    }
}

What is the simplest way of amending

   App\Offer::with('releases')->get();

So as to also get Artist information in each release?

like image 543
thesunneversets Avatar asked Sep 22 '15 17:09

thesunneversets


People also ask

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.

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

How many types of relationships are there in Laravel?

It is basically the interconnection of different tables for data integrity and to avoid redundancy of data. It provides 3 main types of relationships and 2 intermediate types. Let's take a dive into each of these laravel relationships as we describe what they mean and how we can define them.


1 Answers

You can do this by:

App\Offer::with('releases.artist')->get();

You can look at: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations for more information.

If you have multiple releations you can query them by doing:

App\Offer::with(['releases.artist', 'releases.albums'])->get();

When you scrolldown a bit you see

// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();

Remember the "dot" notations is a standard convention of Laravel. For example loading a view:

view('folder.viewfile');

The same applies to eloquents nested relationships.

like image 138
ArjanSchouten Avatar answered Oct 22 '22 10:10

ArjanSchouten