$trell = Trell::find($trell_id);
$builder = $trell->builders();
$codes = $builder->codes(); //Undefined method codes...所以我得到了关于代码的未定义方法,我的关系如下所示:为什么它不能工作?
Trell在模型中有一个定义:
public function builders() {
    return $this->hasOne('Appsales\\Models\\Builders');
}建造商的代码定义如下:
public function codes() {
    return $this->hasMany('Appsales\\Models\\Codes');
}守则包括:
public function builders() {
    return $this->belongsTo('Appsales\\Models\\Builders');
}
$trell->with('builders.codes')->get()->toArray(); works, but I only want "one codes" with some filtering (where in the sql) that is.发布于 2014-03-10 11:40:37
它不起作用,因为对关系函数的调用不是返回模型,而是返回关系。
<?php
$trell = Trell::find($trell_id);
$builder = $trell->builders();
/**
 * $builder is now of type \Illuminate\Database\Eloquent\Relations\HasOne
 * which does not have a method codes()
 * But you don't want the relationship, you want the property as a Model.
 * So you call it as property and not as a function
 */
$builderModel = $trell->builders;
$codes = $builderModel->codes;
/**
 * Now $codes contains all codes as collection of models. If you want to
 * filter them, you get it as Relationship / Query object and use the 
 * regular query builder functions:
 */
$codes = $builderModels->codes()->where('key', $value)->get();您甚至可以从Trell模型加载所有内容:
$trells = Trell::with([
   'builders.codes' => function($query) {
        $query->where('key1', $value1);
   },
])->get();https://stackoverflow.com/questions/22298530
复制相似问题