php Laravel 从多对多关系中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27919239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:36:49  来源:igfitidea点击:

Laravel get data from many to many relation

phplaravelmany-to-manypivot

提问by Jasper Poppe

For a school project, I'm creating a website in the Laravel framework. I can't work with the data from a many-to-many table in my controller.

对于学校项目,我正在 Laravel 框架中创建一个网站。我无法处理控制器中多对多表中的数据。

Here are my models:

这是我的模型:

class Item extends Eloquent {
    public function Tags()
    {
        return $this->belongsToMany('Tag', 'items_has_tags', 'items_id', 'tags_id');
    }
}

class Tag extends Eloquent {
    public function LearningMaterials()
    {
        return $this->belongsToMany('LearningMaterial', 'learning_materials_has_tags', 'tags_id', 'learning_materials_id');
    }
}

I want to iterate all tags from my items in my controller:

我想从我的控制器中的项目中迭代所有标签:

//get all items
$all = Item::where('public', '1')->get();

foreach($allLm as $item){
     $tags = $item->Tags();

     var_dump('will iterate');

     foreach($tags as $t){
         var_dump('will not iterate');
     }
}

What is wrong with my code? How can I handle the tags from my items?

我的代码有什么问题?我如何处理我的物品中的标签?

FYI: I'm creating a search engine. If the user inserts an input value like "mana", all items with tag "management" should be shown.

仅供参考:我正在创建一个搜索引擎。如果用户插入像“mana”这样的输入值,则应显示所有带有“management”标签的项目。

回答by Robo Robok

Laravel's belongsToManymethod queriesrelated models and doesn't get them. That's because you might want to have some additional constraints in your query. What you need to do is:

Laravel 的belongsToMany方法查询相关模型并没有得到它们。那是因为您可能希望在您的查询中有一些额外的约束。你需要做的是:

$tags = $item->Tags()->get();

Or simply:

或者干脆:

$tags = $item->Tags;

回答by lukasgeiter

Calling the relationship function will return a relation object(in this case an instance of BelongsToMany). You can use this to run add further components to your query before running it.
For example:

调用关系函数将返回一个关系对象(在本例中为 的实例BelongsToMany)。您可以使用它在运行之前运行将更多组件添加到您的查询中。
例如:

$only4Tags = $item->Tags()->take(4)->get();

If you want the resultof your relation, call get()or simpler, just use the magic property:

如果你想要你的关系的结果,调用get()或更简单,只需使用魔法属性:

$tags = $item->Tags()->get();
$tags = $item->Tags;