首页 > 解决方案 > 如何正确使用 hasOne 关系?

问题描述

我正在学习 Laravel,我正在尝试创建简单的在线商店。我创建了表格项目和金额。现在我想显示所有物品的库存数量,但由于某种我不知道的原因,物品的数量没有被提取到物品中。

这些是我的表模式:
项目:


    Schema::create('items', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('category_id')->unsigned();
                $table->string('name', 120)->nullable(false);
                $table->float('price',8,2)->unsigned()->nullable(false);
                $table->longText('short_specification');
                $table->longText('specification');
                $table->longText('description');
                $table->string('photo', 100);
                $table->engine = 'InnoDB';

                $table->foreign('category_id')->references('id')->on('categories');
            });

金额:


    Schema::create('amounts', function (Blueprint $table) {
                $table->integer('item_id')->unsigned();
                $table->integer('amount')->unsigned()->nullable(false);
                $table->engine = 'InnoDB';
            });

            Schema::table('amounts',function($table){
                $table->foreign('item_id')->references('id')->on('items');
                $table->primary('item_id');
            });

这些是我的模型:
项目:


    class Item extends Model
    {
        public $timestamps = false;


        function amount()
        {
            return $this->hasOne('App\Amount','item_id','id');
        }
    }

数量:


    class Amount extends Model
    {

        function item()
        {
                 //$this->belongsTo('App\Item');
            return $this->belongsTo('App\Item','item_id','id');
        }
    }

当我做:

$items = DB::table('items')->get();
dd($items);
return view('home')->with('items',$items);

项目显示正确,但项目数量不存在。当我做:


    @foreach($items as $item)

            {{ $item->id }}
            {{ $item->amount }}

    @endforeach

我得到:

未定义属性:stdClass::$amount(查看:D:\2.PROGRAMY\xampp\htdocs\silicon_store\resources\views\home.blade.php) 错误。


从我在网上看到的情况来看(我已经尝试修复这个问题超过 3 个小时,所以我必须做一些完全错误的事情)它应该可以正常工作,但事实并非如此。

标签: phplaravel

解决方案


使用$items = DB::table('items')->get();,您正在使用查询生成器。除非您在查询中加入金额表,否则它不会具有关系的值。

$items = DB::table('items')
        ->leftJoin('amounts', 'items.id', '=', 'amounts.item_id')
        ->get();

我认为您也可以使用 Eloquent 查询。在这种情况下,每个$item都是模型的实例Item而不是 StdClass 对象。

$items = App\Item::with('amount')->get();

推荐阅读