cora cora - 6 months ago 56
MySQL Question

laravel null object hasMany relationship

SOLVED i should not have called out my attributes in the models. For some reason this was keeping it from working.

I have the following structure of two models, Listing and Image. Table Images has FK

listing_id
that references
id
on table Listing.

My Eloquent Model for Listing:

namespace App\Models;

use Illuminate\Database\Eloquent\Model as Model;

class Listing extends Model {

protected $table = 'listings';
protected $connection = 'mysql';

public $id;
public $name;
public $value;
public $itemDescr;
public $user_id;
public $category_id;

protected $fillable = [
'id',
'name',
'value',
'itemDescr',
'user_id',
'category_id'
];

/**
* Return images
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function images()
{
return $this->hasMany('App\Models\Image');
}

}


My Eloquent Model for Image:

namespace App\Models;
use Illuminate\Database\Eloquent\Model as Model;

class Image extends Model
{
protected $table = 'images';
protected $connection = 'mysql';

public $id;
public $imageType;
public $title;
public $filename;
public $path;
public $author_id;
public $listing_id;
public $user_id;
public $size;
public $width;
public $height;


protected $fillable = [
'imageType',
'title',
'filename',
'path',
'author_id',
'listing_id',
'user_id',
'size',
'width',
'height'
];

/**
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function listings()
{
return $this->belongsTo('App\Models\Listing', 'listing_id');
}

}


My controller:

/**
* Return the full list of listings
*
* @param Request $request
*
* @return string
*/

public function itemList(Request $request)
{
$listings = Listing::with('images')->get();

return $listings;

}


I cannot seem to return my listing WITH the image objects -- they are always null. Here is a sample response:


{ id: 6, name: "rare listing item", value: "100", itemDescr: "this is a descr", user_id: 1, category_id: 6,
created_at: "2016-05-30 13:47:33", updated_at: "2016-05-30 13:47:33",
images: [ ] }


The database shows two images with listing_id of 6 for this particular item. I cannot figure out what could be wrong, I've tried nearly all suggestions. Any ideas?

Answer

In Laravel table columns and their values is held in $attributes property, Laravel uses __get() magic method to get the $attributes data. By defining public $listing_id as property on your model it just like telling Laravel: "Hey this is the listing_id and not the one that held $attributes property so please return this instead".

When you define the relationship:

return $this->belongsTo('App\Models\Listing', 'listing_id', 'id');

The public $listing_id property will be returned which is the value is null. Remove those public property definition and it should be works.