Laravel 排除主对象合并
Laravel merge excluding the primary object
我的问题很基础。我知道之前有人问过。但是这些问题的答案曾经在 Laravel 4 中有效,但我无法在 Laravel 5.6.
中有效
我正在尝试合并这两个:
$posts = Post::where('user_id', $user->user_id)->get();
$comments = Comment::where('user_id', $user->user_id)->get();
我试过的方法是这样的:
$activities = $posts->merge($comments)->sortBy('created_at');
这只给我 $comments
在前面的问题中,这似乎在大多数情况下都有效,但在我的情况下却无效。
此外,我知道可以选择
$activities = array_merge($posts->toArray(), $comments->toArray());
但是当我这样做时,我无法再检测到对象属于哪个模型或 table 或不能使用关系。
我愿意接受任何解决方案,但我会喜欢那些我仍然可以使用我的关系的解决方案。
Laravel 5.6
merge()
将 $posts
替换为 $comments
当它们具有相同的主键时。
使用基本集合的 merge()
,它只是在 $posts
:
之后附加 $comments
$activities = $posts->toBase()->merge($comments)->sortBy('created_at');
我的问题很基础。我知道之前有人问过。但是这些问题的答案曾经在 Laravel 4 中有效,但我无法在 Laravel 5.6.
中有效我正在尝试合并这两个:
$posts = Post::where('user_id', $user->user_id)->get();
$comments = Comment::where('user_id', $user->user_id)->get();
我试过的方法是这样的:
$activities = $posts->merge($comments)->sortBy('created_at');
这只给我 $comments
在前面的问题中,这似乎在大多数情况下都有效,但在我的情况下却无效。
此外,我知道可以选择
$activities = array_merge($posts->toArray(), $comments->toArray());
但是当我这样做时,我无法再检测到对象属于哪个模型或 table 或不能使用关系。
我愿意接受任何解决方案,但我会喜欢那些我仍然可以使用我的关系的解决方案。
Laravel 5.6
merge()
将 $posts
替换为 $comments
当它们具有相同的主键时。
使用基本集合的 merge()
,它只是在 $posts
:
$comments
$activities = $posts->toBase()->merge($comments)->sortBy('created_at');