首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一对多,多对多

一对多,多对多
EN

Stack Overflow用户
提问于 2014-03-10 11:10:31
回答 2查看 85关注 0票数 0
代码语言:javascript
运行
复制
$trell = Trell::find($trell_id);

$builder = $trell->builders();

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

所以我得到了关于代码的未定义方法,我的关系如下所示:为什么它不能工作?

Trell在模型中有一个定义:

代码语言:javascript
运行
复制
public function builders() {
    return $this->hasOne('Appsales\\Models\\Builders');
}

建造商的代码定义如下:

代码语言:javascript
运行
复制
public function codes() {
    return $this->hasMany('Appsales\\Models\\Codes');
}

守则包括:

代码语言:javascript
运行
复制
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.
EN

Stack Overflow用户

回答已采纳

发布于 2014-03-10 11:40:37

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

代码语言:javascript
运行
复制
<?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模型加载所有内容:

代码语言:javascript
运行
复制
$trells = Trell::with([

   'builders.codes' => function($query) {

        $query->where('key1', $value1);

   },

])->get();
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22298530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档