tdc
tdc

Reputation: 5464

Laravel 4.1 querying hasMany relationship?

My question is regarding querying relationships in Laravel 4.1 / ORM.

I have a "Labs" model and a "Dates" model. The two are configured to have a 2 way relationship:

Dates.php:

  public function lab(){
    return $this->belongsTo('Labs');
  }

Labs.php:

  public function dates() {
    return $this->hasMany('Dates');
  }

In my controller, I want to query my Labs, and get the Lab which has a date of $today:

$today = new DateTime('today');
$activeLab = Labs::hasDate($today);
return $activeLab;

Something like that... But this of course doesn't work.

How can I retrieve a "Lab" where a Date it owns matches a date I provide?

Thanks for any help!

EDIT: additional code progress..

$today = new DateTime('today');
$today = $today->format('Y-m-d');
$activeLab = Labs::whereHas('dates', function($q) use ($today){
        $q->where('dates.date', $today);
    })->get();

return $activeLab;

Final edit - Solution:

Thanks to deczo we were able to determine the problem. By default Eloquent uses the model name for linking to the foreign key. My model was named Labs (plural), so it looked for labs_id in dates table. You can specify the foreign key in the Labs model hasMany() statement:

public function dates() {
  return $this->hasMany('Dates', 'lab_id');
}

Upvotes: 0

Views: 459

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

$search; // value to find

Lab::whereHas('dates', function ($q) use ($search) {
   $q->where('dates.someColumn', $search);
})->get();

It will return Labs having related date(s) matching given WHERE clause.

Change the relation on Labs:

public function dates() {
  return $this->hasMany('Dates', 'lab_id');
}

Upvotes: 1

Related Questions