首页 > 解决方案 > 使用外键检索数据 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'
    ];
}

标签: phpmysqlreactjslaravel

解决方案


您还需要获取类别:

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' );
}

推荐阅读