Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a belongsToMany() query from a collection ? MySQL/Laravel

Tags:

php

mysql

laravel

I'm using Laravel 5.4.22 (the newest one). In MySQL, I have two tables, tag_categories and tags, which form a many-to-many relationship. What I need is a query which returns all the tags for the selected categories. I know how to solve this when I have only one object, and I know how to solve this with querying and looping each of those objects, but there has to be a query or eloquent based solution for the whole thing?

I understand the code below doesn't work because I'm using ->belongsToMany on a collection rather than an object, but how to I bridge this gap the simplest way?

$resultingTags = TagCategory::whereIn('id', $chosenCategoriesIds)
                              ->belongsToMany(Tag::Class)->get();

dd($resultingTags);
like image 507
Marko Antonić Avatar asked May 16 '17 14:05

Marko Antonić


People also ask

What is belongsToMany in Laravel?

As a rule of thumb, if you use a belongsToMany relationship, it can only be paired with another belongsToMany relationship and means that you have a third pivot table. If you use a hasMany relationship, it can only be paired with a belongsTo relationship and no extra database tables are required.

What is use of query () in Laravel?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.


1 Answers

belongsToMany generally belongs in the model class, not a method called on the fly. When looking to eager load the relationship, you then call the with() method on the query builder.

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

ex:

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

// Query
$users = User::with('roles')->get();
$rolesOfFirstUser = $users->first()->roles;

If you're trying to get all the tags of the given categories, then you should be querying tags, not tag_categories.

Tag::whereHas('categories', function ($query) use ($chosenCategoriesIds) {
    $query->whereIn('id', $chosenCategoriesIds);
})->get();
like image 136
Devon Avatar answered Oct 26 '22 23:10

Devon