CREAZPRO CREAZPRO - 3 months ago 9
PHP Question

How can i get the related data via the model?

I want to simply have a loop which have a sub-loop with all of the images link to the

project. project.id = images.model_key
in my case.

So i was trying to do something which didn't work.

function index()
{
$projects = Project::all();
foreach($projects as $project)
{
echo "<pre>";
print_r($project->images);
echo "</pre>";
}
}


Im the project model.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use App\ProjectCategoryProject;
use App\Models\Image;

class Project extends Model

{

public $fillable = ['id', 'title','description', 'home_page', 'display'];

public function categories()
{
return $this->hasMany('App\ProjectCategoryProject');
}


public function images()
{
return $this->hasMany('App\Models\Image');
}

...


So i guess i have to specify in the model that
project.id = images.model_key
but how ?

Error :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images.project_id' in 'where clause' (SQL: select * from `images` where `images`.`project_id` = 4 and `images`.`project_id` is not null)
Thanks, sorry i'm guetting confused.

Answer

By default Laravel tries to guess the column name from current model, so in a model Project it will presume the column for it's ids in other models to be project_id. You can however override this and explicitly specity the columns to use for relationship:

public function images()
{
    // specify a foreign key to use
    return $this->hasMany('App\Models\Image', 'model_key'); 
}

Or this if you wanna be fully explicit.

public function images()
{
    // specify a foreign key to use
    return $this->hasMany('App\Models\Image', 'model_key', 'id'); 
}

I would however strongly encourage you to abide by laravel "convention" for better readability and easier maintenance. If possible, just rename the column :).