简体   繁体   English

laravel中多对多关系如何正确检索数据?

[英]How correctly retrieve the data in laravel in many to many relationship?

I have a many to many relationship with a pivot table. 我与数据透视表有很多关系。

goods 产品

id | title | ...

tags 标签

id | title | ...

good_tag good_tag

id | good_id | tag_id | ...

How correctly retrieve all goods and their tags in laravel? 如何在laravel中正确检索所有商品及其标签?

Thanks 谢谢

Ok, first lets write the relationships in your models: 好的,首先让我们在模型中编写关系:

Good Model( representing goods table) 好模型(代表商品表)

public function getTags()
{
    return $this->belongsToMany('Tag','good_tag','good_id','tag_id');
}

Tag Model (representing tags table), this is reverse relationship to get goods for a specific tag 标签模型(代表标签表),这是获取特定标签商品的反向关系


public function getGoods()
{
    return $this->belongsToMany('Good','good_tag','tag_id','good_id');
}

Now to retrieve all goods and their tags here's the code: 现在要检索所有商品及其标签,下面是代码:

    $goods=Good::All();  
    foreach($goods as $good)
    {
        echo $good->title;
        echo "Tags: ";
        foreach($good->getTags as $tag)
        {
            echo $tag->title." ";
        }

    }

With Eager Loading 渴望加载

$goods = Good::with('tags')->get();

foreach ($goods as $good) {
    // each goods
    echo $good->title;

    foreach ($good->tags as $tag) {
        // each tag for that goods
        echo $tag->title;
    }
}

Each returned Good model will have its collection of Tags attached. 每个返回的Good模型都将附加其标签集合。

Docs - Eloquent - Eager Loading Docs-雄辩的-渴望加载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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