如何访问与另一个表Laravel 5.1相关的一列

时间:2015-12-08 11:08:25

标签: php mysql laravel laravel-5 laravel-5.1

我有3个模型,Trials有一个样本,track有一个试用版,我需要访问样本名称,我尝试这样做但得到这个错误:

  

Builder.php第2024行中的BadMethodCallException:调用undefined   方法Illuminate \ Database \ Query \ Builder :: samples()

控制器:

public function track($id){
        $tracks = track::with('trials')->with('samples')->where('trials_id',$id)->get();

        return view('Tracks.index',compact('tracks'));
    }

样品:

class samples extends Model
{
    protected $fillable = ['variety'];

    public function Trials()
    {
        return $this->belongsTo('App\trial');
    }

试验:

class trial extends Model
{
    protected $fillable = ['amount','date','comments','code'];

    public function Samples()
    {
        return $this->hasOne('App\samples', 'id', 'samples_id');
    }

    public function Track()
    {
        return $this->belongsTo('App\track');
    }
}

:跟踪:

class track extends Model
{
    public function Trials()
    {
        return $this->hasOne('App\trial', 'id', 'trials_id');
    }
}

1 个答案:

答案 0 :(得分:0)

试试吧

$tracks = track::with('trials.samples')->where('trials_id',$id)->get();

参考: - Nested Eager Loading