亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用外鍵檢索數據 laravel react

使用外鍵檢索數據 laravel react

PHP
拉丁的傳說 2023-04-28 13:54:35
我在 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' );
}


查看完整回答
反對 回復 2023-04-28
  • 1 回答
  • 0 關注
  • 106 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號