gpt4 book ai didi

mysql - SQLSTATE[42S22] : Column not found: 1054 Unknown column 'categories.sub_category_id' in 'where clause' -- Laravel 5

转载 作者:行者123 更新时间:2023-11-29 02:43:45 24 4
gpt4 key购买 nike

我有两个表类别和子类别,我想显示该类别及其连接的子类别。为此,我创建了一个查询。当我尝试使用一对多关系从类别表中获取类别名称时,它显示错误。

表格结构如下
类别;身份证、姓名
子类别:id、category_id、subname

// Category.php model   
class Category extends Model
{
protected $primaryKey = 'id';
protected $table = "categories";

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

// Subcategory.php model
class SubCategory extends Model
{
protected $primaryKey = 'id';
protected $table = "subcategories";

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

// Category Controller
public function show()
{
$categories= Category::all();
$subcategories=Subcategory::all();
return view('show',compact('categories','subcategories'));
}

// show.blade.php
@foreach($subcategories as $subcategory)
{{ $subcategory->subname }}
{{ $subcategory->category_id }}
{{ $subcategory->category->name }}
@endforeach

这一行给我错误 {{ $subcategory->category->name }}

最佳答案

i need to change hasmany to belongsTo

你是right因为子类别只有一个类别,你需要使用 belongsTo 关系

class SubCategory extends Model
{
protected $primaryKey = 'id';
protected $table = "subcategories";

public function category()
{
return $this->belongsTo('App\Category');
}
}

关于mysql - SQLSTATE[42S22] : Column not found: 1054 Unknown column 'categories.sub_category_id' in 'where clause' -- Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com