我想在视图中显示所有用户的个人资料,然后他们发布。很简单:
@foreach($profiles as $profile)
{{ $profile->name }}
@foreach($profile->posts as $post)
{{$post->title}}
@endforeach
@endforeach
但是我只想显示最新的帖子(-> orderBy('created_at','desc')-> limit(4)),只显示接受的帖子(-> where('accept',1))。我该怎么办?
答案 0 :(得分:0)
您已经拥有所需的东西。您只需要将它们放在一起。
@foreach($profile->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get() as $post)
我会考虑在您的个人资料模型上创建一个query scope。这样,您可以执行类似$ profile-> latestPosts之类的事情。
或者您可以使用该关系来返回所需的信息。
public function latestPosts() {
return $this->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get();
}
然后您可以将其用作:
@foreach($profile->latestPosts() as $post)
{{$post->title}}
@endforeach
答案 1 :(得分:0)
您需要在控制器上添加一些类似的代码:
$profiles = Profile::with(['posts' => function ($query) {
$query->where('accept', 1)
->orderBy('created_at', 'desc');
}])->get();
并将其添加到刀片文件:
@foreach($profiles as $profile)
{{ $profile->name }}
@foreach($profile->posts as $post)
{{$post->title}}
@if ($loop->iteration == 4)
@break
@endif
@endforeach
@endforeach
答案 2 :(得分:0)
更好的解决方案是在控制器中加载配置文件时延迟加载所需的帖子。
$profile = Profile::with(['posts' => function ($post) {
$post->where('accept', 1)->orderBy('created_at', 'desc')->limit(4);
}])->limit(10)->get();
然后在刀片中您可以执行与以前相同的操作
@foreach($profiles as $profile)
{{ $profile->name }}
@foreach($profile->posts as $post)
{{$post->title}}
@endforeach
@endforeach
如果您想为latestAccepted
使用范围,则可以使用Post
模型
class Post extends Model
{
public function scopeLatestAccepted($query)
{
return $query->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)
}
}
然后懒加载它
$profile = Profile::with(['posts' => function ($post) {
$post->latestAccepted();
}])->limit(10)->get();
答案 3 :(得分:0)
//控制器
Public function ViewPost(){
$data['data']=DB::table('useratable')
->where('useratable.username','=', $uname)
->where('useratable.password','<=',$pwd)
->leftjoin('posttable', 'useratable.idusertable', '=', 'posttable.userid')
->orderby('posttable.idposttable','desc')
->get();
}
//路线
Route::get('/view-post','YourController@ViewPost')
//视图
@foreach($data as $r)
{{ $r->fullname}} <br>
{{ $r->email}} <br>
{{ $r->topic }} <br>
{{ $r->content }} <br>
{{ $r->datetime}} <br>
...
@endforeach