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