【问题标题】:filling a select field with model with certain tag - laravel用具有特定标签的模型填充选择字段 - laravel
【发布时间】:2015-08-30 08:39:27
【问题描述】:

选择带有特定标签的模型没有问题

        $lis = Capacitytype::find(124)->entities()->orderBy('name','asc')->get();

在我的Capacitytype 模型中,我有这个关系:

public function entities()
{
    return $this->belongsToMany('App\Models\Entity', 'entity_capacitytypes', 'capacitytype_id', 'entity_id');
}

我的问题: 我希望使用相同的选择 f 模型来填写表单中的选择字段。 (我用select2.js)

当我尝试实现这段代码时

        $lis = array(null => 'Commitee') + Capacitytype::find(124)->entities()->orderBy('name','asc')->lists('name', 'id')->all();

我得到这个错误:

SQLSTATE[23000]:完整性约束违规:1052 字段列表中的列“id”不明确(SQL:从entities 中选择nameidentity_capacitytypesentity_capacitytypesid = entity_capacitytypes.entity_id 其中entities.deleted_at 为空,entity_capacitytypes.capacitytype_id = 6 order by name asc)

我试图通过在我的代码中添加表名来解决这个问题,但这是我所能做到的: ->lists('entities.name', 'entities.id')

我的问题: 如何修改代码以获取我的选择字段所需的集合?

谢谢。

【问题讨论】:

    标签: mysql forms laravel collections laravel-5.1


    【解决方案1】:

    您可以利用 Laravel 的 with() 执行预加载作为解决此问题的方法。为此,只需将关系的名称(即entities)传递给方法:

     Capacitytype::find(124)->with('entities')->orderBy('name','asc')->lists('entities.name', 'entities.id');
    

    或者,您可以先获取记录,然后重新格式化以匹配您的用例:

    $list = Capacitytype::find(124)->entities()->orderBy('name','asc')->get()->toArray();
    

    因此,您可以refine 返回的数组列表,以匹配您的 id => name 格式(因此,可以替代lists 方法)。

    $refinedList = array();
    foreach($list as $entity){
         $refinedList[$entity['id']] = $entity['name'];
    }
    

    然后,你去。

    【讨论】:

    • 呃...我无法正确实施。第一个解决方案:生成一个空集合。令人惊讶的是,集合中的项目数量(以及我选择字段中的项目)似乎是正确的。第二种解决方案:在我的选择中不产生任何项目。我使用下面的代码 @foreach($refinedList as $l)
    • 对于第一种方法,显示dd($list),以查看它在您的控制器或视图中是否为空集合。对于第二种方法,您应该这样访问数组项:首先迭代为@foreach($refinedList as $id => $name),然后:<option value="your url/" . {{ $id }}>{{ $name }}</option>
    • 在我的控制器中我有 $list = Capacitytype::find(124)->entities()->orderBy('name','asc')->get()->toArray(); 当我做 dd($list) 我只得到空括号:[]
    • 好吧,如果你得到[],这意味着ID为124的Capacitytype没有任何entities与之相关。无论如何,很高兴它对你有用。
    • “ID 为 124 的容量类型没有任何与之相关的实体” - 我确认。他们在我的斗争中被删除了。很抱歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多