Laravel与自定义主键无关的一对多关系

时间:2014-06-09 20:56:01

标签: php mysql orm laravel-4 eloquent

我正试图在laravel中实现一对多的关系 我的表具有自定义主键名称而不是id

我也设置了$primartKey属性,但这些关系似乎不起作用。

activities
|act_ID|act_acc_ID|.........

categories
|acc_ID|.......

以下是我的模特

class Adventure extends \Eloquent {


    /**
     * @var string $table the name of the table
     */
    protected $table = 'activities';

    /**
     * @var string $primaryKey the primary key of the table
     */
    protected $primaryKey = 'act_ID';

    /**
     * @var bool timestamps updated_at and created_at columns flag
     */
    public $timestamps = false;

    /**
     *
     */
    public function category(){
        $this->belongsTo('Category','act_acc_ID');
    }
}


class Category extends \Eloquent {

    /**
     * @var string $table the name of the table
     */
    protected $table = 'categories';

    /**
     * @var string $primaryKey the primary key of the table
     */
    protected $primaryKey = 'acc_ID';

    /**
     * @var bool timestamps updated_at and created_at columns flag
     */
    public $timestamps = false;

    public function adventures(){
        $this->hasMany('Adventure','act_acc_ID');
    }
}

现在,当我尝试从冒险或冒险中访问类别时,我会获得

  

关系方法必须返回一个类型的对象   照亮\数据库\锋\关系\关系

我在这里做错了什么? 有很多冒险,其类别是15,所以我尝试 我尝试Categories::find(15)->adventures也试过了Categories::find(15)->adventures()

2 个答案:

答案 0 :(得分:3)

您没有使用return关键字,它应该是这样的:

public function category(){
    return $this->belongsTo('Category','act_acc_ID');
}

public function adventures(){
    return $this->hasMany('Adventure','act_acc_ID');
}

在两种关系方法中添加return关键字。

答案 1 :(得分:0)

您必须在类别模型中设置它

public $incrementing = false;