Laravel 5:模型关系问题

Laravel 5: troubles with models relationships

我正在尝试创建一个简单的 Laravel 5 应用程序用于测试目的。 一切似乎都 set-up 正确(数据库、表等)。 但是,在尝试通过关系查询我的数据库时,我仍然遇到以下错误:

PHP ARTISAN 修补匠:

>>> App\Product::first()->name;
=> "Laptop A"

>>> App\Product::first() -> order -> id;
PHP error:  Trying to get property of non-object on line 1
>>> App\Product::first() -> order -> status;
PHP error:  Trying to get property of non-object on line 1

这是我的表(迁移):

public function up()
{
Schema::create('orders', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->string('status');
});


Schema::create('products', function(Blueprint $table)
{
$table->increments('id');
$table->integer('orders_id')->unsigned();
$table->timestamps();
$table->string('name');
$table->string('sn');
});

这是我的 2 个模型:

//文件:App\Order.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model {

public function products()
{
return $this->hasMany('App\Product');
}

}

//文件:App\Product.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

public function order()
{
return $this->belongsTo('App\Order');
}
}   

有人可以帮我理解为什么它不起作用吗? 非常感谢!

您的外键名称不符合约定(应该是单数,order_id),因此您必须指定它:

public function order()
{
    return $this->belongsTo('App\Order', 'orders_id');
}

(反比同理)


另请注意,如果没有订单与产品关联,first() 将 return null。在实际代码中,建议检查 first() 的 return 值是否为 null