如何从Laravel关系中获取数据而不将其加载到初始模型中

8wtpewkr  于 2023-06-30  发布在  其他
关注(0)|答案(4)|浏览(97)

我知道标题可能有点不清楚,所以这里有一个例子。假设我有一个用户和一个帖子。一个用户有很多帖子。如果不向用户模型中添加帖子字段,我将如何获取帖子。
编辑:
我现在意识到我的问题不清楚。我完全理解如何定义关系,我的问题给出了下面的代码

$user = User::where('id', 1)->with('posts')

这里发生的事情是,$user现在有一个名为posts的属性,其中包含属于用户的所有帖子。我不想这样我想做的事情如下

$user = User::where('id', 1);
$posts = $user->posts;
return response(['user' => $user, 'posts' => $posts])

问题是$user仍然具有posts属性。我不想让它变成那样。
EDIT我所说的拥有posts属性的意思如下
在调用$user->posts之前,$user看起来像:

['id' => 1, 'name' => 'jacob']

调用$user->posts

$user = ['id' => 1, 'name' => 'jacob', 'posts' => ['id' => 1, 'user_id' => 1]]

我想要一个检索帖子的方法而不需要修改$user对象

sbdsn5lh

sbdsn5lh1#

编辑

使用laravel集合forget()

$user = User::where('id', 1)->with('posts')->first();
$posts = $user->posts;
$user = collect($user)->forgot('posts')->all(); // this is what you must do. Be careful, this is now an array.
return response(['user' => $user, 'posts' => $posts]);

用户

id  |  name
1   |  John
2   |  Adam

poststable

id  |  user_id  | title
1   |     1     | post_1
2   |     3     | post_2
3   |     1     | post_3

在本例中,用户有很多帖子。并且帖子属于用户。

用户::class

public function posts() {
    return $this->hasMany(Post::class); // this will bind 'user_id' from the posts table to the 'id' of the users table
}

Post::class

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

然后,您可以通过

@foreach($user->posts as $post)
    {{ $post->title }}
@endforeach
vsnjm48y

vsnjm48y2#

为了最有效地从数据库中检索数据并最终得到“平面”数组,您仍然应该使用关系来检索它们,如下所示:

$user = User::where('id', 1)->first();
$posts = $user->posts;
return response(['user' => $user->makeHidden('posts'), 'posts' => $posts])

如果你出于某种原因不想利用关系

$user = User::where('id', 1)->first();
$posts = Post::where('user_id', $user->id)->get();
return response(['user' => $user, 'posts' => $posts])
b4qexyjb

b4qexyjb3#

你可以通过使用资源来实现这一点
1-首先创建新的用户资源:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            "user"=>[
              'id' => $this->id,
              'name' => $this->name,
              'email' => $this->email,  
              ],
            "posts"=>$this->posts
        ];
    }
}

2-在您的控制器中:

$users = User::with('posts')->get()
 return UserResource::collection($users);

Laravel文档

ua4mk5z4

ua4mk5z44#

使用unset方法,帖子关系将被删除:

$user = User::where('id', 1)->first();
$posts = $user->posts;
// remove posts relation from user collection
unset($user->posts);
return response(['user' => $user->makeHidden('posts'), 'posts' => $posts]);

相关问题