【问题标题】:How to store data using relation in laravel?如何在 laravel 中使用关系存储数据?
【发布时间】:2015-09-08 09:32:25
【问题描述】:

我有两张桌子

帖子

id|post_title|post_content

post_images

id|images|post_id

控制器

public function AddPost(Request $request)
    {
        Post::create($request->all());
        // PostImage::create();
        return Redirect::to('Post');
    }

我还添加了关系

class Post extends Model
{
protected $table = 'posts';

    public function images()
    {
        return $this->hasMany('App\PostImage');
    }
}


class PostImage extends Model
{
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

我有一个表单,我可以在其中添加帖子标题、帖子内容并选择多个图像。我的问题是如何在 post_images 表中存储帖子图片和帖子 ID?

【问题讨论】:

    标签: php laravel laravel-5.1


    【解决方案1】:

    在你的控制器中尝试 AddPost 函数(使用 Form 模型绑定)

        $post = new Post($request->all());
        PostImage::post()->images()->save($post);
    

    或者我认为你也可以这样做

    public function AddPost(Post $post, Request $request)
    {
        $input = Input::all();
        $input['post_id'] = $post->id;
        PostImage::create( $input );
        return Redirect::to('Post');
    }
    

    【讨论】:

    猜你喜欢
    • 2015-12-07
    • 2021-07-17
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2019-07-16
    • 2015-03-22
    相关资源
    最近更新 更多