简体   繁体   English

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

[英]Laravel get data from many to many relation

For a school project, I'm creating a website in the Laravel framework. 对于学校项目,我正在Laravel框架中创建一个网站。 I can't work with the data from a many-to-many table in my controller. 我无法处理控制器中多对多表中的数据。

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”标签的所有项目。

Laravel's belongsToMany method queries related models and doesn't get them. Laravel的belongsToMany方法查询相关模型,但没有得到它们。 That's because you might want to have some additional constraints in your query. 那是因为您可能希望在查询中有一些额外的约束。 What you need to do is: 你需要做的是:

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

Or simply: 或者干脆:

$tags = $item->Tags;

Calling the relationship function will return a relation object (in this case an instance of BelongsToMany ). 调用关系函数将返回一个关系对象 (在本例中是BelongsToMany的实例)。 You can use this to run add further components to your query before running it. 您可以使用它在运行之前运行向查询添加更多组件。
For example: 例如:

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

If you want the result of your relation, call get() or simpler, just use the magic property: 如果你想要你的关系的结果 ,调用get()或更简单,只需使用magic属性:

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

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

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