HasMany Through a Many to Many

Posted: 2015-07-29 15:43:14

This thread helped a lot http://laravel.io/forum/03-04-2014-hasmanythrough-with-many-to-many

In the end I had this query

   class MetaData extends Model 
{


    public function meta_values()
    {
        return $this->belongsToMany(\App\MetaValue::class);
    }

    public function meta_data_types()
    {
        return $this->belongsToMany(\App\MetaValue::class)
            ->leftJoin('meta_data_type_meta_value', 'meta_values.id', '=', 'meta_data_type_meta_value.meta_value_id')
            ->leftJoin('meta_data_types', 'meta_data_types.id', '=', 'meta_data_type_meta_value.meta_data_type_id')
            ->groupBy('meta_data_types.id')
            ->select('meta_data_types.*');
    }

Model meta_data_types had not direct relation to this MetaData model class. But MetaData did relate to meta_values.

So using that info I could get the related MetaValues and then the related MetaDataTypes and that was it.

It is a lot easier if just doing this through a One to Many http://laravel.com/docs/5.1/eloquent-relationships#has-many-through


Tags:

laravel php