我在 mysql 中有兩個表,一個名為 category,帶有 id 和 name(例如 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。
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
您還需要獲取類別:
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' ); }
- 1 回答
- 0 關注
- 106 瀏覽
添加回答
舉報
0/150
提交
取消