简体   繁体   中英

In Laravel Eloquent how to define relationship through secondary table? (Always returning 0 relations)

I feel like this should work. I have a list of products and categories (types).

Tables:

Products
    - id
    - name
    - etc
Types
    - id
    - name
    - etc
ProductTypes
    - product_id
    - type_id

Now, I feel like in the Type model in Laravel, I should be able to define this relationship:

public function products()
{
    return $this->hasManyThrough(Product::class, ProductType::class, 'type_id', 'id');
}

I've tried other variations with the secondary ids in the additional parameters but no luck, always an empty list. Is ProductTypes a pivot table and therefore should be dealt with differently?

Edit: What's weird is that for the final 2 parameters ( $localKey = null, $secondLocalKey = null ) even if I enter complete garbage no error is thrown but these 2 parameters $firstKey = null, $secondKey = null have to be correct).

You are using the wrong relationship. Based on your database structure, a product can belong to many type. Therefore, it should be a BelongsToMany instead of a HasManyThrough .

You can achieve what you want with the following method, by passing the table name of your ProductTypes as the second parameter:

public function products()
{
    return $this->belongsToMany(Product::class, 'product_types');
}

If your ProductType model extends Illuminate\Database\Eloquent\Relations\Pivot , you can do:

public function products()
{
    return $this->belongsToMany(Product::class, 'product_types')
        ->using(ProductType::class);
}

For more information about Many to Many relationships: https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM