【问题标题】:laravel result of 2 objects in one array一个数组中2个对象的laravel结果
【发布时间】:2017-04-10 16:49:15
【问题描述】:

我有 2 个对象,第一个检索对象作品的 cmets,第二个检索对象成就的 cmets。我想在包含 cmets 列表的单个表中显示结果。

$posts1 =\DB::table('posts')
->select('posts.*', 'profils.nom_profil', 'works.titre', 'profils.imagelogo', 'works.description', 'works.like', 'works.nlike')
->join('works', 'posts.work_id','=','works.id')
->join('profils', 'posts.profil_id','=','profils.id')
->where('works.profil_id',$id)
->orderBy('posts.id', 'desc')
->paginate(10);

$posts2 =\DB::table('posts')
->select('posts.*', 'profils.nom_profil', 'achievs.titre', 'profils.imagelogo', 'achievs.description', 'achievs.like', 'achievs.nlike')
->join('achievs', 'posts.achiev_id','=','achievs.id')
->join('profils', 'posts.profil_id','=','profils.id')
->where('achievs.profil_id',$id)
->orderBy('posts.id', 'desc')
->paginate(10);

在视图中:

@foreach($posts as $post)
.
.
.
@endforeach

【问题讨论】:

  • 你应该将 ->get() 添加到两个查询中,先将它们变成集合,然后才能合并。

标签: php sql laravel eloquent query-builder


【解决方案1】:

对此可能有很多sloution,但最简单的一个是将对象merge 为:

$posts = $posts1->merge(posts2);

更新

尝试合并为:

$posts= $posts1->merge($posts2->all())

【讨论】:

  • 我有这个错误尝试在视图中获取非对象的属性@foreach($posts as $post) {{($post->visit == '0')}}:跨度>
  • 你应该将 ->get() 添加到这两个查询中,以使它们首先成为集合,然后你可以合并
  • 我有这个错误调用一个非对象的成员函数merge()。当我为两者添加 ->get() 时!
  • 检查更新的答案。如果这不起作用,请在合并后显示dd($posts) 的结果。
  • 它可以工作,但是如何进行分页?当我为两者添加 ->get() 时,我也有此错误 Call to a member function merge() on a non-object!
【解决方案2】:

如果您不使用 Laravel 5.3,使用 get 将返回 @iCode 提到的结果数组,那么您可以使用本机 array_merge。

$posts = array_merge($posts1->get(),$posts2->get());

或将 get() 方法添加到您的查询中,然后执行

$posts = array_merge($posts1,$posts2);

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 2015-11-19
    • 1970-01-01
    • 2018-06-14
    • 2019-09-28
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多