已解决我不应该在模型中调用我的属性。由于某种原因,这使它无法工作。
我有以下两个模型的结构:列表和图像。表图像具有引用表 Listing 上的 id
的 FK listing_id
。
我的 Eloquent 列表模型:
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');
}
}
我的 Eloquent 图像模型:
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');
}
}
我的 Controller :
/**
* Return the full list of listings
*
* @param Request $request
*
* @return string
*/
public function itemList(Request $request)
{
$listings = Listing::with('images')->get();
return $listings;
}
我似乎无法返回带有图像对象的列表 - 它们始终为空。以下是响应示例:
{ 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: [ ] }
数据库显示该特定商品的 Listing_id 为 6 的两张图像。我无法弄清楚可能出了什么问题,我几乎尝试了所有建议。有什么想法吗?
最佳答案
在 Laravel 表列中,它们的值保存在 $attributes
属性中,Laravel 使用 __get()
魔术方法来获取 $attributes
数据。通过将 public $listing_id
定义为模型上的属性,就像告诉 Laravel:“嘿,这是 listing_id
,而不是保存 $attributes
的属性。 > 属性(property),因此请返回此”。
定义关系时:
return $this->belongsTo('App\Models\Listing', 'listing_id', 'id');
将返回 public $listing_id
属性,其值为 null
。删除那些公共(public)属性定义,它应该可以工作。
关于php - Laravel null 对象 hasMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37552290/