【问题标题】:Laravel 5: troubles with models relationshipsLaravel 5:模型关系的麻烦
【发布时间】:2015-05-27 20:44:36
【问题描述】:

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

PHP 工匠修补匠:

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

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

【问题讨论】:

    标签: model relationship laravel-5


    【解决方案1】:

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

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

    (反比关系也一样)


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多