我在获取有关商品的信息时遇到了一些问题。我在论坛上的stakoverflow阅读了很多信息。也许我找不到正确的信息。也许有人知道解决问题的方法 我有4张桌子
public function up()
{
Schema::create('db_items', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_weapons', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('grade_id')->unsigned();
$table->foreign('grade_id')
->references('id')->on('db_item_grades')
->onDelete('cascade');
$table->string('hand')->nullable();
$table->string('name')->nullable();
$table->text('description')->nullable();
$table->string('icon')->nullable();
$table->string('p_atak')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_db_item_category', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')
->references('id')->on('db_item_categories')
->onDelete('cascade');
$table->timestamps();
});
}
还有3个模型
class DbItem extends Model
{
function weapon()
{
return $this->hasOne(DbItemWeapon::class, 'item_id');
}
function categories()
{
return $this->belongsToMany(DbItemCategory::class,'db_item_db_item_category','item_id','category_id');
}
}
class DbItemWeapon extends Model
{
function DbItem()
{
return $this->belongsTo(DbItem::class);
}
}
class DbItemCategory extends Model
{
function items()
{
return $this->belongsToMany(DbItem::class,'db_item_db_item_category','category_id','item_id')->with('weapon');
}
}
当我尝试获取一些信息时,例如wotrks
@foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
@foreach( $category->items as $item)
<p>{{ $item->id }}</p>
@endforeach
</div>
</li>
@endforeach
我获得了包含其商品的类别,并且我可以查看类别中包含的商品ID,但是如果我想查看更多信息,则它不起作用 $ item->武器->名称
答案 0 :(得分:0)
也许某些items
没有weapon
,请先检查weapon's
是否存在:
@foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
@foreach( $category->items as $item)
@php
$weapon = $item->weapon;
@endphp
<p>{{ $item->id }}</p>
<p>{{ $weapon ? $weapon->name : null }}</p>
@endforeach
</div>
</li>
@endforeach