首页 > 解决方案 > 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');
    }
}

请协助。

标签: phplaravelphp-5.4laravel-6.2

解决方案


以下规则将为您提供帮助。

  • 始终以小写字母开头的关系名称。为类而不是方法节省大写。

  • 模型应该是单一的

  • 注意名称的多个。应该只有其中之一的事物应该是单数的。因此,在您的 1:1 关系中,两个关系名称都应该是单数。

AdvertItem 类

    public function item(){
        return $this->belongsTo(Item::class);
    }

那么,如果你有 Item 并且想要 AdvertItem,你load应该

$item->load('advertitem');

或相反

$advertItem->load('item');

推荐阅读