php - 使用外键检索数据 laravel react
问题描述
我在 mysql 中有两个表,一个名为类别的 id 和名称(例如 1 Dress)
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
第二个表叫衣服,带有外键 category_id(例如 1,Black Dress,very cool,10.99,/images.img1,10,1)
public function up()
{
Schema::create('clothes', function (Blueprint $table) {
$table->increment('id');
$table->string('item');
$table->string('description');
$table->double('price');
$table->string('img');
$table->integer('stock');
$table->integer('category_id');
});
Schema::table('clothes', function($table) {
$table->foreign('category_id')->references('id')->on('categories');
});
}
所以我正在尝试使用名称类别反应获取信息。
componentDidMount(){
axios.get('product')
.then(response => {
this.setState({ products: response.data });
})
.catch(function (error) {
console.log(error);
})
render(){
return (
<div className="container">
<h5>Products</h5>
<br />
<div className="row justify-content-center">
{this.state.products.map((data,mykey)=>
<div className="card" key={mykey}>
<img className="card-img-top" src={data.img}></img>
<div className="card-body">
<h4 className="card-title"><b>{data.item}</b></h4>
<p className="card-text">{data.description}</p>
<ul className="list-group list-group-flush">
<li className="list-group-item"><b>Price: {data.price}$</b></li>
<li className="list-group-item"><p>{data.category_id} <Button>Yess</Button></p></li>
</ul>
</div>
</div>
)}
</div>
</div>
)
}
在 web.php 中
Route::get('product', function(){ return App\Clothes::all(); });
通过这种方式,我得到的只是类别的数量,但我想获得类别的名称。
我将不胜感激任何类型的想法或帮助来获得类别名称而不仅仅是 id。
更新:: Clothes.php
class Clothes extends Model
{
//
protected $fillable = [
'id', 'item','description','price','img','stock', 'category_id'
];
}
分类.php
class Category extends Model
{
//
protected $fillable = [
'id', 'name'
];
}
解决方案
您还需要获取类别:
Route::get('product', function(){ return App\Clothes::with('category')->get(); });
如果正确定义模型和关系,这将起作用。
在布料模型中添加:
public function category()
{
return $this->belongsTo('App\Category', 'category_id' );
}
在类别模型中添加:
public function clothes()
{
return $this->hasMany('App\Clothes', 'category_id' );
}
推荐阅读
- python - Python模块'scm'没有属性'Open'
- regex - 使用 Dockerhub Regex 进行自动构建
- json - 解析包含 json 字符串的 json
- kubernetes - Kubernetes 的 pod 状态为 CrashLoopBackOff 但没有显示日志
- firebase - 我在运行我的应用程序(Flutter、FireBase)时收到此 E/flutter (25055) 错误
- oracle10g - Oracle 形成 10g OLE2 或 CLIENT_OLE2
- intellij-idea - Intellij - 配置为使用 Maven Wrapper 时找不到有效的 Maven 安装
- database - 如何检查firestore中文档的大小?
- linux - 使用 yum 以不同用户身份安装 Tomcat
- android - NestedScrollView 内的 RecyclerView 一次只显示 1 个元素