【问题标题】:create list for dropdown with value from relationed table使用相关表中的值创建下拉列表
【发布时间】:2016-01-25 18:34:43
【问题描述】:

我的模型产品返回类似这样的东西

  • id = 1
  • name = 产品名称
  • category_id = 101
  • 类别 = 数组
    • id = 101
    • name = 电子产品

我需要使用lists() 来创建这样的东西:

lists("category.name", "id")

但看起来这是不可能的。如何为这样的下拉列表创建列表:

1 = electronics
2 = furniture
3 = cars
...

非常感谢

【问题讨论】:

  • “Category”是属于“Product”的模型吗?如果是这样,您是要列出所有类别,还是仅列出一部分类别?
  • 产品属于类别和类别有很多产品。我试图列出属于每个产品的类别名称的产品 ID。

标签: laravel laravel-5 eloquent


【解决方案1】:

你确定你建立了正确的关系吗?因为这正是lists() 通常所做的事情,而且创建这样的列表远非不可能。
很难理解你是如何在没有代码的情况下设计 Eloquent 逻辑的,但假设你已经设置了 category_product 数据透视表,我将如何处理你的情况。
给定两个模型,ProductCategory,我会定义这两个关系原因,据我所知,一个产品可以有多个类别,一个类别可以与多个产品相关联:

class Product extends Model
{
   ////////
   public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
   ////////
}  

class Category extends Model
    {
       ////////
       public function products()
        {
            return $this->belongsToMany('App\Product');
        }
       ////////
    }  

此时,您可以开始了,您只需

Product::findOrFail($id)->categories->lists('name','id')  

这将返回一个数组,其中包含与给定产品关联的所有类别

array:[
    1 => first-category
    2 => second-category
    3 => third-category
    ....
  ]  

请注意,如果您想获取与给定类别匹配的所有产品的列表,那么通过此设置,它也会以相反的方式工作

Category::findOrFail($id)->products->lists('name','id')  

在答案的最上面,我假设您确实设置了数据透视表,但如果您没有设置,这里有一个快速提示: 在您的产品迁移中

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            //
        });

        Schema::create('category_product', function (Blueprint $table){
            $table->integer('category_id')->unsigned()->index();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->timestamps();
        });
    }  

然后migrate 现在一切都已正确设置。最后但同样重要的是,如果您要使用此迁移,您需要修复模型中的关系,这取决于您的应用程序逻辑:假设流程是创建一个新产品 -> 选择其中的类别创建表单,则需要在 category 方法中添加timestamps()

return $this->belongsToMany('App\Category')->withTimeStamps(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多