donglian3055 2015-12-11 18:21
浏览 20

Laravel - 通过其他方式访问关系

I have the following tables:

entries  
- id 
- category_id 
- name  

field  
 - id  
 - category_id
 - name  

field_values  
- id  
- entry_id  
- field_id  
- value   

category  
 - id  
 - name

Each Category has certain fields. If I add an entry, I choose the category and I can enter the values for the field for the entry.

Let's say we have the Category "Venues". Venues has the custom field named "Capacity". If I add a news entry, I need to fill the field "Capacity".

This is how I read the fields and their values for an entry:

@foreach($data->field_values as $values)
    {{$values->field->name}}: {{$values->value}}
@endforeach  

I can only access the field table through the "field_values" table. Isn't it possible to access field directly from entry maybe with an hasManyThrough ?

This (in Entry Model):

public function fields()
{
    return $this->hasManyThrough('App\Field', 'App\FieldValues');
}

throws the following mysql error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fields.field_values_id' in 'on clause' (SQL: select `fields`.*, `field_values`.`entry_id` from `fields` inner join `field_values` on `field_values`.`id` = `fields`.`field_values_id` where `field_values`.`entry_id` in (3))

Why I need to add a field_values_id to Field? Isn't there a different approach?

I just want to foreach through entry->field and not do it by entry_field_values->field

  • 写回答

1条回答 默认 最新

  • dongwo5449 2015-12-11 21:53
    关注

    If you just want to access the Fields for an entry, why not do a hasMany relationship ?

    Entry Model:

    public function fields()
    {
        return $this->hasMany('App\Field');
    }
    

    Then you can get all the fields for an entry as:

    $fields = $entry->fields()->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制