php - Laravel 关系似乎不起作用
问题描述
我在 Laravel 中有一个 Item 和 AdvertItem 对象。我想在商品和广告商品之间建立一对一的关系
项目类看起来像这样
<?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');
推荐阅读
- javascript - 单选按钮不会选中/取消选中
- javascript - 如何在 javascript 中制作和引用配置文件
- python - 无法在谷歌协作中的 tensorflow 中训练完整批次
- javascript - 如何使用 jQuery 删除脚本
- c# - EF Core 6 ThenInclude 引用错误
- javascript - JavaScript 中的语法 x:y 是什么意思?
- javascript - 按下 Enter 按钮后将光标保持在文本框上
- javascript - 为什么 WebView.evaluateJavascript 方法被调用了两次?
- python - 无法安装scrapy
- swift - 如何在快速长按集合视图的特定行时打开视图?