Laravel Eloquent 关系混乱

Laravel Eloquent Relationship Confusion

这是我的情况;

由于我使用的是 Laravel,这里是我的控制器方法,用于查看特定客户端的所有协议;

public function index($client_id)
{
    $client_agreements = Agreement::find($client_id);

    return View::make('client_agreements.index')
        ->with('client_agreements', $client_agreements);
}

这是我的Agreement模型;

class Agreement extends Eloquent {

    protected $table = 'agreements';

    public function client_agreements(){

        return $this->hasMany('ClientAgreement', 'agreement_id');
    }

}

所以我想在 agreements table;

的视图中输出

和来自 client_agreements table;

我的视图代码(我确定是错误的但不知道为什么)本质上是;

@foreach($client_agreements as $client_agreement)
    <tr>
        <td>{{ $client_agreement->agreement_type }}</td>
        <td>{{ $client_agreement->level }}</td>
        <td>{{ $client_agreement->start_date }}</td>
        <td>{{ $client_agreement->expire_date }}</td>
    </tr>
@endforeach

我做错了什么?

你可以这样做:

$client = Client::with('agreements')->find($client_id);
$client_agreements = $client->agreements;
return View::make('client_agreements.index')
           ->with('client_agreements', $client_agreements);

在您看来:

@foreach($client_agreements as $client_agreement)
    <tr>
        <td>{{ $client_agreement->agreement_type }}</td>
        <td>{{ $client_agreement->level }}</td>
        <td>{{ $client_agreement->pivot->start_date }}</td>
        <td>{{ $client_agreement->pivot->expire_date }}</td>
    </tr>
@endforeach

这需要以下设置:

客户端模型

class Client extends Eloquent {

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

协议模型

class Agreement extends Eloquent {

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

有关详细信息,请阅读 Eloquent docs(尤其是关于关系的部分)