尝试在提交帖子时将Users名称从Users表中检索,并将firstname插入到字段作者下的Posts表中。我不认为我会正确地做到这一点。
发布模型
public function insertPost($input)
{
$validation = new Services\Validators\Post;
if ($validation->passes())
{
$post = Post::create($input);
// Get the logged in user from the users table and save it to the posts table author field
$name = Post::get()->user->firstname;
$author = $input['author'];
$post->author = $name;
$post->save();
}
public function user()
{
return $this->belongsTo('User', 'firstname');
}
用户模型(关系定义为Post模型)
public function posts()
{
return $this->hasMany('Post', 'author');
}
答案 0 :(得分:0)
您正尝试实例化 Post :: create 。如果你想要Post模型的实例,你应该:
$post = new Post
另请参阅您是否实际向用户提供了Post模型?
答案 1 :(得分:0)
您可以尝试此操作(只有登录的用户可以提交帖子,因此从登录的用户对象中获取名称):
if ($validation->passes())
{
$name = Auth::user()->firstname; // Get logged in user's first name
$input = array_merge(array('author' => $name), $input);
return $post = Post::create($input);
}
您也可以像这样创建新帖子:
$post = new Post;
$post->title = Input::get('title'); // or $input[['title'] if $input is available
$post->author = Auth::user()->firstname;
// ... do same for all fields, assign values to each field, then save
return $post->save();