试图通过Laravel

时间:2017-12-23 10:25:37

标签: php mysql laravel-5.4 relationship

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

public function userProfil($id)

我有一个profile函数,它从userprofile表中获取数据。在里面我有以下代码用于保存数据:

$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从文章表中获取文章时,它不起作用如下:

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

它给出的错误就像:

  

此集合实例上不存在属性[article_id]。

虽然savearticle表有article_id但是我可以在没有上面的行的情况下输出它,在视图中我得到它们:

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

它为我提供了savearticle表中的所有内容,我可以执行savedarticle->article_id并获取article_id但无法在控制器中获取它。

我正在使用Laravel 5.4。

2 个答案:

答案 0 :(得分:1)

错误消息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());

答案 1 :(得分:0)

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

如果是这样,那么你必须做以下事情。

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

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

这将允许您获取属于用户的所有帖子。

2:在帖子中,模型定义了如下所示的用户关系。

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

这将允许您获得帖子用户;

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)方法中,您将拥有用户数据以及用户发布数据。现在,如果您想获得帖子关系,那么只需定义如下。比方说一篇文章也属于一篇文章。

4:在帖子中,模型定义了获取文章的关系。

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

现在,您可以在找到用户时获得该文章。请看下面。我正在重写控制器显示动作,以便您更好地理解。

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. 
}

   }

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