简体   繁体   English

创建新帖子时获取用户 ID

[英]get user id when created a new posts

i wanted to retrieve id from Users Table for user_id field in Posts table我想从用户表中为 Posts 表中的 user_id 字段检索 id

i've already tried with Auth::id();我已经尝试过 Auth::id(); but its retrieving current authenticated Id但它检索当前经过身份验证的 Id

so what i wanted is, when i created new data, the id from Users to be displayed at user_id Field in Posts Table所以我想要的是,当我创建新数据时,来自用户的 id 将显示在帖子表的 user_id 字段中

This is my Post model:这是我的帖子模型:

public function user()
{
    return $this->belongsTo(User::class);
}    

This is my User Model:这是我的用户模型:

public function posts()
{
    return $this->hasMany(post::class);
}

and this is how i currently stored my data:这就是我目前存储数据的方式:

$post = new post;
    // $post->parent_id = $request->input('id');
    $post->user_id = Auth::id(); 
    $post->type = $request->input('type');
    $post->slug = str_slug($request->input('title'));
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->excerpt = $request->input('excerpt');
    $post->image = $imageName;
    $post->tag = $request->input('tag');
    $post->metas = $request->input('metas');
    $post->ispublished = $request->input('ispublished');
    $post->published_at = $request->input('published_at');
    $post->save();

how do i exactly do what i want?我该怎么做我想做的事?

// edited i'm new to this so i got my questions all wrong, // 编辑我是新手,所以我的问题都错了,

i already got what i want by using Auth::id.我已经通过使用 Auth::id 得到了我想要的东西。 i just wanted to record the id of the creator of the posts我只是想记录帖子创建者的 ID

your question isn't clear exactly, but you can use relationship to this work like :您的问题尚不清楚,但您可以使用与这项工作的关系,例如:

$user->post()->create([
    $post->type = $request->input('type');
    $post->slug = str_slug($request->input('title'));
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->excerpt = $request->input('excerpt');
    $post->image = $imageName;
    $post->tag = $request->input('tag');
    $post->metas = $request->input('metas');
    $post->ispublished = $request->input('ispublished');
    $post->published_at = $request->input('published_at');
]);

This solution isn't really good in terms of performance because it uses join.这个解决方案在性能方面并不是很好,因为它使用了连接。

Check your routes to the controller if it has middleware.如果控制器有中间件,请检查它的路由。 To retrieve user data through Auth middleware is required.需要通过 Auth 中间件检索用户数据。

Example例子

Route::post('/', 'PostController@store')->middleware('auth:users');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM