Back

eloquent relations


johnef posted 4 months ago

I have two tables one is templates and the other is template_images

Showing migration of the two tables.

Templates

Schema::create('templates', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title', 155);
            .....
});

Template Images

Schema::create('template_images', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('template_id')->unsigned();
            $table->boolean('master');
            $table->binary('image');
$table->foreign('template_id')->references('id')->on('templates')->onDelete('cascade');
            ...
        });

I have made relations in the both Models like this

Template-Model

class Template extends Model
{
public function tempImage()
    {
        return $this->hasMany('App\Models\TemplateImage', 'template_id');
    }
}

Template Image-Model

class TemplateImage extends Model
{
public function tempImage ()
    {
        return $this->belongsTo('App\Models\Template', 'template_id');
    }
}

What I want is

Select all from templates and select from template_images where template_images.template_id = templates.id and template_images.master = 1

Update This is how I need to get the image in blade

$temp->tempImage->image

What I try in my controller

$temps = Template::query()->with('tempImage')->get();

but still cant get it the right way.

jay4yam replied 4 months ago

Because you've got many TemplateImage for one Template, you need to iterate over the Temp object in your view. like this...

@foreach($temps->tempImage() as $tempImage)
    $tempImage->image
@endforeach

if you want to get the 1st result you can do this in your view

$temps->->tempImage()->first()->image

And in your TempImage, you 've got a fonction which have the same name in the Template model, in the templaimage, you get the template model so i think this function must be named temp() (its the inverse relation) :

class TemplateImage extends Model
{
public function temp ()
    {
        return $this->belongsTo('App\Models\Template', 'template_id');
    }
}

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us