如何做Laravel ORM关系数据库

时间:2015-11-04 14:47:00

标签: laravel-4.2 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

任何人都可以帮助我为什么会收到此错误?

1 个答案:

答案 0 :(得分:1)

你在调用现实时错过了()。

dd($cat->test()->first()->image()->first()->src);