我在Laravel中有一个Item和AdvertItem对象。我想在商品和广告商品之间建立1对1的关系
item类看起来像这样
<?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关系中,两个关系名称都应为单数。
AdvertItem类
public function item(){
return $this->belongsTo(Item::class);
}
然后,如果您有Item并想要AdvertItem,则应load
它
$item->load('advertitem');
或反过来
$advertItem->load('item');