繁体   English   中英

如何做 Laravel ORM 关系数据库

[英]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.

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