简体   繁体   中英

How to do Laravel ORM Relational Databases

I have a category table that contains :

Schema::create('categories',function($table){
    $table->increments('id');
    $table->string('name',25);
    $table->timestamps();
});

and product table :

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();
});

and 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();
});

And my models :

Category:

class Category extends Eloquent{
    public function Test() {
        return $this->hasMany('Product');
    }
}

Product:

class Product extends Eloquent
{
    public function category(){
        return $this->belongsTo('Category');
    }

    public function images() {
        return $this->hasMany('Images');
    }
}

Now I want to show each category in a div with first product photo.

Route::get('test',function(){
    $category = Category::all();
    foreach($category as $cat){
        dd($cat->Test->first()->images->first()->src);
    }
});

but i receive this error :

Trying to get property of non-object

Could any one help me why I get this error ?

你在调用 realtion 时错过了 ()。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM