[英]How to do Laravel ORM Relational Databases
我有一個類別表,其中包含:
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
任何人都可以幫助我為什么會出現此錯誤?
你在調用 realtion 時錯過了 ()。
dd($cat->test()->first()->image()->first()->src);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.