一对多,多对多

时间:2014-03-10 11:10:32

标签: laravel

$trell = Trell::find($trell_id);

$builder = $trell->builders();

$codes = $builder->codes(); //Undefined method codes...

所以我在代码上获得了Undefined方法,我的关系如下:为什么它不起作用?

Trell在模型中定义了一个:

public function builders() {
    return $this->hasOne('Appsales\\Models\\Builders');
}

Builder已定义代码:

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.

2 个答案:

答案 0 :(得分:0)

方法$builder = $trell->builders();未返回构建器对象,它返回一个查询构建器对象,因此当它查找 codes()方法时,它不会存在。

$builder = $trell->builders;替换该行应该有效。

答案 1 :(得分:0)

它不起作用,因为对关系函数的调用不返回模型而是返回关系。

<?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();