Search code examples
laraveleloquenteloquent-relationship

Laravel define join relation as a model relation


I have a scenario:

Movie::join('stream_urls', function ($join) {
        $join->on('stream_urls.movie', '=', 'movies.filename');
});

I want to define it as a function in the model as I want joined data to be returned as a JSON array. So I want something like this;

$movie = Movie::where('is_active', 1)
        ->with('urls')
        ->orderBy('movies.id', 'DESC')->get();

How to define this 'urls()' function in the model?


Solution

  • You define a relationship in the Movie model.

    This looks like a one to many relationship.

    If you stick to naming conventions you only need to specify the class

    hasMany(Child::class);
    

    But since you use the stream_url.movie and movie.filename columns, you're going to need to specify them as the optional parameters.

    hasMany(Child::class, 'foreign_key', 'local_key');
    

    I'm assuming the model mapping the table stream_urls is called StreamUrl.

    class Movie extends Model
    {
        public function urls()
        {
            return $this->hasMany(StreamUrl::class, 'movie', 'filename');
        }
    }
    

    Now you can eager load this relationship by using Movie::with('urls').