I have two tables:
items
id
name
description
created_at
update_at
images
id
name
item_id
created_at
updated_at
I did build a one-to-one relationship between the Item
model and Image
model.
Item
model
<?php
namespace App/Models;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use AppModelsImage;
class Item extends Model
{
use HashFactory;
public function image()
{
return $this->hasOne(Image::class, "item_id");
}
}
Image
model
<?php
namespace App/Models;
use AppModelsItem;
use IlluminateDatabaseEloquentFactoriesHasFactory;
class Item extends Model
{
use HashFactory;
public function item()
{
return $this->belongsTo(Item::class);
}
}
Controller
<?php
namespace AppHttpControllers;
use IlluminateHttpReuquest;
use IlluminateSupportFacadesDB;
class RootController extends Controller
{
$items = DB::table("items")->get();
return view("index", ["items" => $items]);
}
In The view I wanted to show the image name of each item, therefore I proceeded the following way,
<div>
@foreach($items as item)
<span>{{ $item->image->name }}</span>
@endforeach
</div>
I, despite my checkings and analyses, couldn’t figure out where I was wrong in this code.
2
Answers
Thank you very much, everything worked out when changed the query builder DB to the Item:all().
should be:
Using the
DB
facade instead of the Eloquent model means none of your model’s functionality or settings apply to the resulting query.