Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get data from many to many relation

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.

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.

like image 803
Jasper Poppe Avatar asked Jan 13 '15 09:01

Jasper Poppe


People also ask

How do you fetch data from many to many relationships?

Try this one: SELECT book_title, subject_name FROM Book INNER JOIN Book_Author ON Book. book_ISBN = Book_Author. book_ISBN INNER JOIN Author ON Book_Author.

What is polymorphic relationship laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is hasMany in laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .


2 Answers

Laravel's belongsToMany method queries related 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:

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

Or simply:

$tags = $item->Tags;
like image 84
Robo Robok Avatar answered Oct 10 '22 18:10

Robo Robok


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:

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

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

$tags = $item->Tags()->get();
$tags = $item->Tags;
like image 25
lukasgeiter Avatar answered Oct 10 '22 16:10

lukasgeiter