Toby Joiner
Toby Joiner

Reputation: 4376

Get model data based on pivot table column

# TABLES:
# kids: name, birthday, active
# chores: name, start_age, number_of_kids_required
# chore_kid: chore_id, kid_id, chore_date

Kid.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kid extends Model
{
    public function chores(){
        return $this->belongsToMany('App\Chore')
            ->withPivot('chore_date')
            ->withTimestamps();    
    }
}

Chore.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Kid;

class Chore extends Model
    public function kids(){
        return $this->belongsToMany('App\Kid')
            ->withPivot('chore_date')
            ->withTimestamps();
    }
}

With belongs to many I can grab the chores with assigned kids and the pivot table having the requested chore date:

$chore->kids()->wherePivot('chore_date', $date);

How can I get all the chores with the same chore_date without limiting it to the kids that are assigned to a specific chore.

How do I do this? This is my guess at this but it doesn't work:

Chore::wherePivot('chore_date', $date);

I have tried other combinations, but can't seem to find the right syntax.

Upvotes: 0

Views: 63

Answers (1)

punk73
punk73

Reputation: 378

controller

$chore = Chore::whereHas('kids', function ($query) use ($date){
   $query->where('chore_date','=', $date );
})->get();

with that you'll get chore with specific date. hope that help.

Upvotes: 1

Related Questions