当我使用Laravel eloquent - 关系(One To Many)时,结果为NULL。 我在" work_hour"中设置了数据。表,其中" workers_id"有价值2,并且"工人" id为2的表 我按照文档" Laravel relationships"
我的架构如下所示:
public function up()
{
Schema::create('work_hour', function($table){
$table->increments('id');
$table->integer('worked_hour');
$table->time('worked_from');
$table->time('worked_to');
$table->integer('workers_id')->unsigned();
$table->foreign('workers_id')->references('id')->on('workers');
$table->integer('workday_id');
$table->integer('offer_id');
});
}
PS:列workday_id,offer_id不设置为外国,但是!
模型看起来像这样:
class Worker extends Eloquent{
protected $fillable = ['first_name', 'last_name'];
}
class Workhour extends Eloquent{
protected $table = 'work_hour';
public function worker(){
return $this->belongsTo('Worker','workers_id');
}
}
控制器 PS:我在SO上搜索了同样的问题,我尝试了一些意见,然后我对它们进行了评论
class WorkerController extends BaseController {
protected $table = 'workers';
....
public function show($id){
$worker = Worker::find($id);
// $workhour = Workhour::where('workers_id','=',$worker->id)->get();
// casting the result: works $workhour->toArray()
// $workhour = Worker::find($id)->with('workhour')->get();
//Call to undefined method Illuminate\Database\Query\Builder::workhour()
// $workhour = Worker::with('workhour')->where('id',2)->get();
//Call to undefined method Illuminate\Database\Query\Builder::workhour()
$workhour = Worker::find($id)->workhour;
// null
dd($workhour);
return View::make('worker.show',['worker' => $worker,'workhour'=>$workhour]);
}
public function workhour(){
return $this->hasMany('Workhour','workers_id');
}
}
我打电话给" show.blade.php"与" ... / public / worker / 2" (Laravel 4) 我究竟做错了什么?
答案 0 :(得分:1)
您只需将关系添加到模型而不是控制器:
class Worker extends Eloquent{
protected $fillable = ['first_name', 'last_name'];
public function workhour(){
return $this->hasMany('Workhour','workers_id');
}
}