laravel - 按活动日期而不是用户关注的顺序
问题描述
我有两张表,活动表和关注表。我想获得“关注”活动的创建日期,而不是创建用户的日期。
Schema::create('activities', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->index();
$table->integer('activity_id')->index();
$table->string('activity_type', 50);
$table->timestamps();
$table->index(['activity_id', 'activity_type']);
});
Schema::create('followings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->unsignedBigInteger('follower_id');
$table->dateTime('followed_date')->nullable();
$table->dateTime('unfollowed_date')->nullable();
$table->timestamps();
$table->unique(['user_id', 'follower_id']);
});
现在我有这个代码:
控制器:
$followings = $user->following()->get();
看法:
@foreach($followings->sortByDesc('id') as $following)
@foreach($following->user->activity->sortByDesc('id') as $activity)
@if($activity->activity_type == 'App\Thread')
<li class="activity">
<div class="activity-user">
<p class="avatar" style="background-color: {{ $activity->user->color }}">
{{ substr($activity->user->name, 0, 1) }}</p>
</div>
<div class="activity-body">
<h4><a
href="/profiles/{{ $activity->user->name }}?profile-posts">{{ $activity->user->name }}</a>
published <a
href="/forums/{{ $activity->activity->channel->slug }}/{{ $activity->activity->slug }}/">
{{ $activity->activity->title }}</a></h4>
<p>
{!! BBCode::parse($activity->activity->body) !!}
</p>
<p class="created-at">
{{-- {{ $activity->activity->created_at->format('l') }}
at
{{ $activity->activity->created_at->format('h:i A') }} --}}
{{ $activity->activity->created_at->format('M j, Y') }}
</p>
</div>
</li>
@endif
@endforeach
@endforeach
模型:
public function following()
{
return $this->hasMany(Following::class);
}
无论如何,我是否可以通过活动日期而不是以下()日期到达多态表并排序?
现在,它会根据用户发布日期的姓名返回记录,但我希望严格按照活动进行。
解决方案
我是这样做的:
控制器
$followings = $user->following()->get();
foreach($followings as $following) {
foreach($following->user->activity as $activity) {
$followingArray[] = $activity->id;
}
}
//dd($followingArray);
if(!empty($followingArray)){
$following = Activity::whereIn('id', $followingArray)->orderBy('created_at', 'desc')->get();
} else {
$following = '';
}
看法:
@if(!empty($following))
@foreach($following as $activity)
推荐阅读
- c# - 如何将列表加载到 ComboBox DataGrid 中并显示另一个列表中的选定值?
- php - 只有一个按钮的表格
- python - 将foursquare场地类别层次结构JSON转换为pandas daframe直到显示所有不同级别的任何简单方法?
- mysql - 编写一个 SQL 查询来查找并显示在同一类别下连续 2 个订单的客户?
- reactjs - 如何在反应测试库中测试我的组件中的组件
- python - nltk.stem 没有属性“Stemmer”
- asp.net - 在 ASP.Net 路由参数处理中指定格式说明符?
- css - 是否可以在包装器显示中使 div 可见:none div 而不更改包装器 div
- python - 从无限循环函数传输结果以供其他 python 函数使用
- google-sheets - 具有可变输入的 Google 表格中的间接单元格引用