dreamwind1985 2015-11-14 00:22
浏览 40
已采纳

laravel用外键填充选择框

There are 3 tables

Sizes
id
name

Products
id
name

Product_sizes
id
product_id
size_id

I want to fill an selectbox with the id of product_sizes and the name of the foreign key connected table size.

for exampe:

product_sizes.id    1
sizes.name          medium

where medium would be found by size_id in product sizes. How can I the name value in the list?

What i currently have

I can get the right row with

 $sizes =  $product->sizeAvailable()->lists('pr', 'size_id');

where sizeAvailable is a relation that returns all product_sizes for a selected product.

  • 写回答

1条回答 默认 最新

  • douxi4114 2015-11-15 12:47
    关注

    First of all you don't need an id field in the pivot table because you can uniquely identify each row with the composite key product_id, size_id. A Product can belong to many Sizes and a Size can belong to many Products, thus you shouldn't have duplicate rows.

    The relationships of each model are like the following:

    class Product extends Model {
        public function sizeAvailable() {
            return $this->belongToMany('Size', 'product_sizes');
        }
    }
    
    class Size extends Model {
        public function products() {
            return $this->belongToMany('Product', 'product_sizes');
        }
    }
    

    Finally in your View you can use Blade functions to generate your selectbox:

    <select>
        @foreach($product->sizeAvailable() as $size)
            <option value="{{ $size->id }}">{{ $size->name }}</option>
        @endforeach
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站