正在尝试通过 Laravel 中的相关 table 获取数据

Trying to get data via related table in Laravel

我想做的是在个人资料中显示用户保存的帖子。我将尝试参考我的代码尽可能好地解释它。所以:

public function userProfil($id)

我有从 userprofile table 获取数据的配置文件功能。在里面我有以下保存数据的代码:

$authed = User::find($id);
$savedarticles = $authed->mysaves;
$allsavings = DB::select("Select * from article where id=$savedarticles->id");

但是这段代码无论如何都不是这样工作的。我可以这样做:

$authed = User::find($id);
$savedarticles = $authed->mysaves;

但是当我尝试使用 mysaves 的 article_id 从文章 table 中获取文章时,它不起作用,如下所示:

$allsaved= DB::table('article')->where('id', $savedarticles->article_id);

它给出的错误如下:

Property [article_id] does not exist on this collection instance.

虽然 savearticle table 有 article_id 我可以在没有上面的行的情况下输出它并且我认为它们是:

@foreach($savedarticles as $savedarticle)
    <p>{{$savedarticle}}</p>
@endforeach

它为我提供了保存文章 table 中的所有内容,我可以执行 savedarticle->article_idarticle_id 但无法在控制器中获取。

我正在使用 Laravel 5.4。

错误消息 Property [article_id] does not exist on this collection instance. 表示您正在尝试从集合中获取单个实例的属性。

例如,集合可能像

[$article1, $article2, $article3]

因此您尝试做的事情类似于

[$article1, $article2, $article3]->article_id

您正在尝试从集合而不是单个实例中获取属性。

对于您的查询,您可以使用 where in sql 语句来搜索与数组中的任何项目匹配的行

$allsaved= DB::table('article')->whereIn('id', $savedarticles->pluck('article_id')->all());

我理解的是A USER有很多POSTS,一个POST属于一篇文章。

如果这是真的,那么您必须执行以下操作。

1:在 USER 模型中定义一个关系来获取所有 posts。如下所示。

public function posts() {
   // Foreign key will be a key that is stored in posts table and represent the user MAY BE: user_id
   $this->hasMany(Posts::class, 'foreign_key', 'local_key')
}

这将允许您获得属于某个用户的所有 post。

2:在posts中,模型定义了如下用户关系。

public function user() {
   $this->belongsTo(User::class, 'foreign_key', 'local_key');
}

这将使您获得 post 用户;

3:现在在你的控制器中,你会有这样的东西。

public function show($user_id) {

      // find a user with posts as eager loading(to avoid query again)
      $user = User::with(['posts'])->where('id', $user_id)->first();

      // get all posts that belong to this user
      $posts = $user->posts; 
   }

在控制器 show($user_id) 方法中,您将拥有用户数据以及用户 posts 数据。现在,如果你想获得 post 关系,那么只需如下定义即可。假设 post 也属于一篇文章。

4:在posts中,model定义了一个获取文章的关系。

public function article() {
  // This will allow you to get a post artcle
  $this->belongsTo(Article::class, 'foreign_key', 'local_key');
}

现在您可以在查找用户的同时获取文章。请看下面。我正在重写 controller show action 以使您更好地理解。

5: 获取用户 user_id

public function show($user_id) {

// find a user with posts as eager loading(to avoid query again)
// eager loading for posts & post child, this will give you NOSQL at runtime and all data will come from one query. 
          $user = User::with(['posts', 'posts.article'])->where('id', $user_id)->first();

          // get all posts that belong to this user
          $posts = $user->posts; 
foreach($posts as $post) {
  $article = $post->article; // Child relation of post. 
}

   }

希望您能理解流程,您必须确保模型相关才能完美运行。如果您需要进一步的帮助,请告诉我。