我在 Laravel 中有一個(gè) Item 和 AdvertItem 對(duì)象。我想在商品和廣告商品之間建立一對(duì)一的關(guān)系項(xiàng)目類看起來(lái)像這樣<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Item extends Model{ // public function Category(){ return $this->belongsTo(Category::class); } public function Currency(){ return $this->hasOne(Currency::class); } public function AdvertItem(){ return $this->hasOne(AdvertItems::class); }}AdvertItem類看起來(lái)像這樣<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class AdvertItems extends Model{ protected $guarded = []; // public function items(){ return $this->belongsTo(Item::class); }}但是當(dāng)我調(diào)用 advertItem 時(shí),我只看到 item_id = 1 而不是 item 對(duì)象。項(xiàng)目表是這樣創(chuàng)建的 class CreateItemsTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('items', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('description'); $table->unsignedBigInteger('currency_lookup_id'); $table->unsignedBigInteger('category_id')->index(); $table->unsignedBigInteger('price'); $table->string("image_path"); $table->string('sale_ind'); $table->Date('eff_from'); $table->Date('eff_to'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('item'); }}廣告表是這樣創(chuàng)建的class CreateAdvertItemsTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('advert_items', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('item_id'); $table->unsignedBigInteger('customer_id'); $table->Date('eff_from'); $table->Date('eff_to'); $table->timestamps(); }); }
1 回答
收到一只叮咚
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
以下規(guī)則將為您提供幫助。
始終以小寫(xiě)字母開(kāi)頭的關(guān)系名稱。為類而不是方法節(jié)省大寫(xiě)。
模型應(yīng)該是單一的
注意名稱的多個(gè)。應(yīng)該只有其中之一的事物應(yīng)該是單數(shù)的。因此,在您的 1:1 關(guān)系中,兩個(gè)關(guān)系名稱都應(yīng)該是單數(shù)。
AdvertItem 類
public function item(){
return $this->belongsTo(Item::class);
}
那么,如果你有 Item 并且想要 AdvertItem,你load應(yīng)該
$item->load('advertitem');
或相反
$advertItem->load('item');
- 1 回答
- 0 關(guān)注
- 91 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
