与where子句雄辩的关系

时间:2015-01-12 11:10:19

标签: oop laravel eloquent

我需要在中间表的code字段中执行where条件。我的两个模特是;

class Agreement extends Eloquent {

  protected $table = 'agreements';

  public function clients(){ 
    return $this->belongsToMany('Client', 'client_agreements')->withPivot('start_date', 'expire_date', 'code');
  }
}

class Client extends Eloquent {
  public function agreements(){
    return $this->belongsToMany('Agreement', 'client_agreements')->withPivot('start_date', 'expire_date', 'id', 'code');
  }
}

我的控制器目前正在使用;

public function show($code, $client_id)
{
    //
    $client = Client::with('agreements')->find($client_id);

    $client_agreement = $client->agreements;

}

我想我需要扩展$client->agreements;代码,以便在$code上包含where条件。我已经尝试了很多不同的组合,但只是继续返回相同的调用未定义的方法错误。

我尝试了类似的事情;

$client_agreement = $client->agreements->where('code', '=', $code);
$client_agreement = $client->agreements->code->find($code);
$client_agreement = $client->agreements->pivot->code->find($code);

我总是得到同样的错误。我对物体不是那么好,所以也许我看错了。怎么做?

1 个答案:

答案 0 :(得分:3)

您需要访问->relation()而不是->relation(这是动态媒体资源):

$client_agreement = $client->agreements()
                     ->wherePivot('code', '=', $code)
                     ->first();