0
我有一個包含類別表:怎麼辦Laravel ORM關係數據庫
Schema::create('categories',function($table){
$table->increments('id');
$table->string('name',25);
$table->timestamps();
});
和產品表:
Schema::create('products',function($table){
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('name',25);
$table->text('description');
$table->timestamps();
});
和product_image:
Schema::create('images',function($table){
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->string('src',100);
$table->timestamps();
});
而且我的模型:
類別:
class Category extends Eloquent{
public function Test() {
return $this->hasMany('Product');
}
}
產品:
class Product extends Eloquent
{
public function category(){
return $this->belongsTo('Category');
}
public function images() {
return $this->hasMany('Images');
}
}
現在我要顯示與第一產品照片一個div每個類別。
Route::get('test',function(){
$category = Category::all();
foreach($category as $cat){
dd($cat->Test->first()->images->first()->src);
}
});
,但我收到此錯誤:
Trying to get property of non-object
可以在任何一個可以幫助我,爲什麼我得到這個錯誤?
我改變了,但仍然有同樣的錯誤,並且還有dd($ cat-> Test-> first());已經返回NULL – user2647541
你確定表中有記錄嗎?並確保圖像表名稱是圖像 –
也可以嘗試重命名Test()以測試()方法名稱應始終以小寫開頭,其良好的約定 –