php - 如何正确使用 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 个小时,所以我必须做一些完全错误的事情)它应该可以正常工作,但事实并非如此。
解决方案
使用$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();
推荐阅读
- ios - 在不使用 alpha 的情况下使用 UISegmentedControl 在视图 ios 之间切换?
- java - Selenium Webdriver Java 中的 JavascriptExecutor
- gradle - 想清理根目录下的 .gradle 文件夹,我可以安全地删除以前的旧版本文件夹吗?
- javascript - 每次用户进入我的网站时,如何更改我的年龄验证以清除 cookie?
- ansible - 银河角色。在配置的模块路径中找不到模块文件。此外,缺少核心模块
- python-3.x - 如何键入提示 Python 3 元类?
- typescript - Azure Functions 上的 GraphQL 订阅 - 这可能吗?
- python - 如何从看不见的文档中的列表中识别术语
- c# - 在 SWIG 中使用相同的 C# 代码连接调试和发布 DLL?
- html - 使标题 100% 的屏幕