0

我有两个模型公告:

 class Announcement extends Eloquent {

    public function characteristics() {
    $this->hasMany('Characteristic');
    }

}

和特点:

class Characteristic extends Eloquent {
protected $guarded = array();

public static $rules = array();

public function announcement() {
    return $this->belongsTo('Announcement');
}
}

有两张表:

 CREATE TABLE characteristics (
   id integer PRIMARY KEY AUTOINCREMENT,
   title varchar DEFAULT('Количество'),
   announcement_id integer,
   count integer DEFAULT('0'),
   value_name varchar DEFAULT('шт.'),
   created_at datetime,
   updated_at datetime,
   deleted_at datetime
 );

 CREATE TABLE announcements (
   id integer PRIMARY KEY AUTOINCREMENT,
   title varchar DEFAULT(''),
   description varchar DEFAULT(''),
   created_at datetime,
   updated_at datetime,
   deleted_at datetime
 );

它们都带有一些测试数据。

这是我在 routes.php 中的代码:

 Route::get('/', function()
 {
    $test = Announcement::find(1)->characteristics();

    var_dump($test);
 });

但我总是得到NULL。我无法理解,为什么...

4

2 回答 2

1

您必须返回 $this->hasMany('Characteristic', 'announcement_id');

你错过了回报。

于 2013-09-26T12:26:23.053 回答
0

试试这样:

public function characteristics() {
    return $this->hasMany('Characteristic','announcement_id');
}

public function announcement() {
    return return $this->belongsTo('Announcement','announcement_id');
}

函数名称是您的表的名称。第一个参数是模型名称,第二个参数是匹配的键名。

同样为了良好的做法,将外键添加到announcement_id

$table->foreign('announcement_id')->references('id')->on('announcements')->onDelete('cascade');

也尝试这样的查询:

$test = Announcement::find(1)->characteristics; //not a method name
于 2013-09-26T11:59:02.870 回答