如何在自己的类中使用类的实例

时间:2014-07-08 02:08:59

标签: php laravel

在Laravel 4.x中,我有一个客户Eloqeunt模型,它与Customer_tel Eloquent模型有关系:

class Customer extends Eloquent 
{

    public function tel()
    {
        return $this->hasMany('Customer_tel');
    }
}

Customer_tel表有一个布尔列' main'。

当我在视图中创建Customer Class的实例时,我可以使用filter()方法过滤掉主编号:

$Customer = Customer::find(1);

$Customer->tel->filter(function($tel)
    {
        if ($tel->main == true)
        {
            return true;
        }
    })->shift()->tel

但是当我尝试使用filter()方法在类中创建一个函数时:

    public function mainTel() 
    {
        return $this->tel()->filter(function($tel)
        {
            if ($tel->main == true)
            {
                return true;
            }
        })->shift()->tel;
    }

当我尝试在视图$Customer->mainTel中引用它时,它会给我一个错误"Call to undefined method Illuminate\Database\Query\Builder::filter()"

为什么我不能仅在课外但不在课程中过滤实例?有没有正确的方法呢?

1 个答案:

答案 0 :(得分:0)

调用方法(tel())将返回HasMany实例,然后您可以在其上调用查询构建器方法。使用Eloquent的魔法属性,您可以将其短路。因此$customer->tel相当于$customer->tel()->get(),它返回一个集合。这就是为什么它在你的第一个例子中为你工作的原因。

有关详细信息,请参阅the docs


更好的选择是在查询本身中执行此操作:

return $this->tel()->where('main', true)->pluck('tel');

另请注意Eloquent中的you can create your own magic properties

class Customer extends Eloquent {

    public function tel()
    {
        return $this->hasMany('Customer_tel');
    }

    public function getMainTelAttribute()
    {
        return $this->tel()->where('main', true)->pluck('tel');
    }
}

现在有了$customer模型,你可以直接调用你的魔法:

$tel = $customer::find(1)->main_tel;
相关问题