定义与Laravel有一个关系

时间:2014-11-24 14:18:56

标签: laravel laravel-4

我仍然不了解Laravel的关系如何运作,而且我已经花了好几个小时来定义一段关系,但我无法做到这一点,所以我会感激一些帮助。

我的实体是NegotiationOrder。订单有很多协商,我设法正确定义,orders_negotiations表正在正确送达:

class Order extends Eloquent {

    public function negotiations() {
        return $this->belongsToMany('Negotiation', 'orders_negotiations');
    }

}

但是,现在我试图从谈判方面检索订单。我试过这个:

class Negotiation extends Eloquent {

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

}

但是,在执行此操作$negotiation->order->id时,我收到此错误:Trying to get property of non-object

当我尝试hasOne()时,我收到此错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orders.negotiation_id' in 'where clause' (SQL: select * from订单where订单. negotiation_id = 1 limit 1)

我做错了什么,我应该怎么做?

2 个答案:

答案 0 :(得分:1)

所以这就是关系:

  • 订单有许多谈判。
  • 谈判属于 顺序。

我认为Laravel无法使指定关系变得更加简单,因为它几乎就是你说话的方式:

class Order extends Eloquent 
{
    public function negotiations() 
    {
        return $this->hasMany('Negotiation');
    }
}

class Negotiation extends Eloquent 
{
    public function order() 
    {
        return $this->belongsTo('Order');
    }

}

就是这样。当然,通过这种关系,您需要在表格/迁移中指定foreign keys

Schema::create('orders', function(Blueprint $table)
{
    $table->integer('id');
    $table->string('number',64);
});

Schema::create('negotiations', function(Blueprint $table)
{
    $table->integer('id');
    $table->integer('order_id'); //here it is
    $table->string('subject');
    // ... and so on
});

这就是它的全部内容。

答案 1 :(得分:0)

如果要定义belongsToMany关系,则需要设置数据透视表。

http://laravel.com/docs/4.2/eloquent#relationships并查看多对多关系。

除非是一对多关系,否则就这样做。

public function negotiations() {
    return $this->hasMany('Negotiation', 'orders_negotiations');
}