【问题标题】:Laravel 4 model relationship one to many confusionLaravel 4 模型关系一对多混淆
【发布时间】:2014-02-25 18:51:35
【问题描述】:

尝试在用户提交帖子时从用户表中检索用户名字,并将名字插入到字段作者下的帖子表中。我不认为我会正确地处理它。

后模型

 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');
}

【问题讨论】:

    标签: php model laravel laravel-4 foreign-key-relationship


    【解决方案1】:

    您正在尝试实例化 Post::create 。如果你想要 Post 模型的实例,你应该:

    $post = new Post
    

    还看到您实际上是否向 User 提供了 Post 模型?

    【讨论】:

      【解决方案2】:

      你可以试试这个(只有登录用户才能提交帖子,所以从登录用户对象中获取名称):

      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();
      

      【讨论】:

        猜你喜欢
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-10
        • 2015-03-05
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        相关资源
        最近更新 更多