我在使用Laravel中的外键检索值时遇到问题。我的公告表中有一列“creator_id”,它在我的用户表上引用了“id”。对于检索数据的类似尝试我没有遇到任何问题,但这似乎不起作用。 dd($ creator)返回一个大型对象,它确实有我正在寻找的数据,但是我无法使用creator() - >名称来访问它,就像文档说我应该这样。 laravel还是新手,但这就是我目前所拥有的。
控制器中的功能:
public function showBulletin()
{
$creator = Bulletin::find(1)->creator();
dd($creator);
$posts = Bulletin::all();
return View::make('bulletin')->with(array('posts'=>$posts,'creator'=>$creator));
}
公告模型:
<?php
class Bulletin extends Eloquent {
public function creator()
{
return $this->belongsTo('User');
}
public function comments()
{
return $this->hasMany('Comment');// TODO create comments table
}
public function type()
{
//if 1 then, etc
}
}
用户模型:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function tags()
{
//TO REMOVE RECORD
//Tag::find(1)->tags()->detach();
return $this->belongsToMany('Tag');
}
public function createUser()
{
$password = Hash::make('secret');
}
public function bulletin()
{
return $this->hasMany('Bulletin','creator_id');
}
public function profile()
{
return $this->hasOne('Profile');
}
}
以及我用来创建表的迁移功能:
Schema::create('bulletins',function($table)
{
$table->increments('id');
$table->integer('creator_id')->unsigned()->foreign('creator_id')->references('id')->on('users');
$table->integer('comments_id')->unsigned();// todo add foreign key constraint later when comments table is made
$table->integer('type')->unsigned();
$table->mediumText('title');
$table->longText('content');
$table->timestamps();
});
非常感谢
答案 0 :(得分:4)
添加get
方法:
$creator = Bulletin::find(1)->creator()->get();
// or simply
$creator = Bulletin::find(1)->creator;