简体   繁体   中英

Laravel - Eloquent 3 Table Query

I know there are several questions out there on 3 table joins, but the examples are simpler than my set up.

I have three tables: Items , Attributes , Categories .

`item.item_code = attributes.item_code`

`attributes.category_id = category.id`

Using eloquent, I can access attributes no problem with:

$items = Item::with('attributes')->paginate(15);

But I can't seem to get the relationship set correctly to retrieve the category name.

With a standard MySql query I'd use something like:

    SELECT category_name FROM items
    JOIN attributes on items.item_code = attributes.item_code
    JOIN categories on attributes.pg3_id = categories.id 
    WHERE items.item_code = 40992264

How do I achieve this using eloquent?

Edit - My bad - Totally messed up the SQL. Updated to reflect the correct table names and include the second join

Update

My models currently look like this:

class Attributes extends Model
{
    public function category(){

        return $this->belongsTo(Category::class);
    }
}

class Product extends Model
{
    public function item()
    {
        return $this->belongsTo(Item::class);
    }

}

class Category extends Model
{
    public function attributes()
    {
        return $this->belongsTo(Attributes::class);
    }
}

But this still isn't returning a result. I've tried using

$items = Item::with('attributes.category')->get();

as suggested, but this still throws an error. If I update the Product model to:

class Product extends Model
{
    public function item()
    {
        return $this->belongsTo(Item::class);
    }
    public function category(){

        return $this->belongsTo(Category::class);
    }

}

I don't get an error, but the relationship returns null.

You can do

$items = Item::with('attributes.category')->get();

So you access the category relationship inside the attributes relationship.

For example:

foreach ($items as $item) {
    foreach ($item->attributes as $attribute) {
        echo $attribute->category->id; // Will print the category id.
    }
}

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