[英]Laravel relationships seems to not working
我在 Laravel 中有一個 Item 和 AdvertItem 對象。 我想在商品和廣告商品之間創建 1 對 1 的關系
項目類看起來像這樣
<?php
namespace 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類看起來像這樣
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdvertItems extends Model
{
protected $guarded = [];
//
public function items(){
return $this->belongsTo(Item::class);
}
}
但是當我調用 advertItem 時,我只看到 item_id = 1 而不是 item 對象。
項目表是這樣創建的
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');
}
}
廣告表是這樣創建的
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();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('advert_items');
}
}
請協助。
以下規則將對您有所幫助。
始終以小寫開頭的關系名稱。 為類而不是方法節省大寫。
模型應該是單一的
注意名稱的復數。 應該只有其中之一的事物應該是單數。 因此,在您的 1:1 關系中,兩個關系名稱都應該是單數。
廣告項目類
public function item(){
return $this->belongsTo(Item::class);
}
那么,如果你有 Item 並且想要 AdvertItem,你應該load
它
$item->load('advertitem');
或者反過來
$advertItem->load('item');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.