Laravel With and wherePivot

laravel wherepivot closure
laravel eloquent relationships example
laravel where pivot column
laravel relationship with condition
laravel many to many sync
polymorphism in laravel
laravel update related model
laravel touch

I'm trying to extract all companies and contacts with pivot.main_contact = 1.

Tables:

Company: id, name
Company_contacts: id, company_id, contact_id, main_contact
Contacts: id, name

Model:

class Company extends Model
{
        public function mainContact()
    {
        return $this->belongsToMany('App\Contact', 'company_contacts')
                        ->wherePivot('main_contact', '=', 1);
    }
}

Controller:

$query = Company::with('mainContact')->get();   

This returns companies + ALL contacts for the companies and NOT ONLY the ones with main_contact = 1.

Try to add withPivot():

return $this->belongsToMany('App\Contact', 'company_contacts')
    ->withPivot('main_contact')
    ->wherePivot('main_contact', '=', 1);

Eloquent: Relationships - Laravel, I think your implementation of scopeWithPendingReviews() is an abuse of the intended use of scopes. That aside, I believe you're not using  Laravel With and wherePivot. Ask Question Asked 3 years, 6 months ago. Active 1 year, 5 months ago. wherePivot laravel method and “in” operator. 5.

Company::with('mainContact')->get(); returns all compaines and all contacts. You should be doing $company->mainContacts()->get(); instead.

$companies=Company::all();
foreach($companies as $company)
{
   print_r($company->mainContact()->get());
}
die;

Laravel 5 issue with wherePivot, BelongsToMany.php public function wherePivot($column, $operator closure sub queries in wherePivot method laravel/framework#21970. I am working with Laravel 5 and I am having issue getting ->wherePivot() to work on a Many-to-Many relationship. When I dd() the SQL it looks like Eloquent is looking for records in the pivot table with a `pose_state`.`pose_id` is null`.

First, for reasons I'm unsure of, you need to add withPivot('main_contact'); to your relation. This will return main_contact in your collection under pivot

class Company extends Model
{
        public function mainContact()
    {
        return $this->belongsToMany('App\Contact', 'company_contacts')
                        ->withPivot('main_contact');
    }
}

The second thing you need to do is use withPivot() while constraint eager loading like so:

$companies = Company::with(['mainContact'=> function($query){
    $query->wherePivot('main_contact', 1);
}])->get();

I've checked it, it works.

Just to go a bit above and beyond. Sometimes you'll want to query a pivot table without knowing the value. You can do so by:

$companies = Company::with(['mainContact'=> function($query) use ($contact){
    $query->wherePivot('main_contact', $contact);
}])->get();

Allow wherePivot to accept closures for grouped queries · Issue , The other day I was chatting with a coworker about using Laravel Eloquent ORM's wherePivot() method to constrain eager loading using with()  wherePivot laravel method and “in” operator Posted 3 years ago by ahmadbadpey I have two Course and User models that there is a ManyToMany relationship between them.

Eloquent Eager Loading Constrained by Pivot, public function getByPivot($val){ return $this ->wherePivot('pivot_a', '<=', $val) ->​wherePivot('pivot_b' select * from `table_a` where `pivot` = pivot_a and `pivot` = pivot_b Proudly hosted with Laravel Forge and DigitalOcean. Today I want to talk about a feature of Laravel which is really useful but can be potentially difficult to understand at first. Pivot table is an example of intermediate table with relationships between two other "main" tables.

wherePivot using the word 'pivot' instead of the actual table, I've got these two database schemas, I'll dumb them down for now. Schema::​create('matchups', function(Blueprint $table)  Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional constraints on this posts relationship:

Eloquent belongsToMany() with wherePivot() and has , Laravel Relationships pretty much cover everything that a model can users, we can simply call wherePivot() method on the query builder. The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Comments
  • Could you check your mysql query log and copy the raw SQL query into your question?
  • Tried that. It returnt the same result. It is just like when using with everything behing belongsToMany is ignored even; ->orderBy
  • This will create N+1 number of queries (i.e. 10001 queries for table with 10000 rows) instead of just 2. laravel.com/docs/5.3/eloquent-relationships#eager-loading
  • @AlexeyMezenin with eager loading $query->mainContact gives the companies with main_contact 1.
  • Rather just do two queries if possible. (there are a few more relationships to load actually.
  • @Line in Linus foreach($query as $q){ $q->minContact;} will give only the companies with min_contact value 1.