# 顯示微博
本節將為每個人顯示自己發布的微博。
## 關聯查詢
在上一節中,我們定義了
~~~php
// 正向關聯 Post 模型
public function posts()
{
return $this->hasMany('Post', 'user_id');
}
~~~
非常簡單的,在控制器中只需要多加一句 `with('posts')` 即可展示該用戶的所有微博
`application\user\controller\Auth.php`
~~~php
public function read($id)
{
$user = User::with('posts')->find($id);
return $user;
}
~~~
接著,訪問 http://thinkphp.test/user/auth/read/id/1.html ,可以看到一行 `"posts":[]`
這是因為現在 `posts` 表中還未有數據,我們需要為用戶填充一些假數據。
命令行鍵入 `php think seed:create Posts`
`database\seeds\Posts.php`
~~~php
<?php
use think\migration\Seeder;
class Posts extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
$data = [];
for ($i = 0; $i < 200; $i++) {
$user_id = !($i % 2) ? 1 : 2;
$data[] = [
'content' => $faker->text,
'user_id' => $user_id,
];
}
$this->table('posts')->insert($data)->save();
}
}
~~~
上面代碼中,`$i % 2` 表示能否被 2 整除。
創建完畢后運行 `php think seed:run` 再次訪問 http://thinkphp.test/user/auth/read/id/1.html 就可以看到剛剛裝填好的假數據了。
## 前端顯示
現在數據庫中已經有填充好的假數據,我們只需要在前端中輸出即可。
`application\user\controller\Auth.php`
~~~php
public function read($id)
{
$user = User::with(['posts' => function ($query) {
$query->limit(8);
$query->order('created_at', 'desc');
}])->find($id);
$this->assign([
'user' => $user,
'session' => Session::get('user')
]);
return $this->fetch();
}
~~~
注意,`with(['posts' => function ($query)` 是一個閉包操作,下面的 `limit` 等語句都是針對關聯模型 `posts` 操作而不是 `User`
切換到前端頁面
`resources\views\user\auth\read.blade.php`
~~~html
@extends('_layout.default')
@section('title', $user->name)
@section('content')
<div class="panel panel-default list-group-flush">
<div class="panel-heading">
<h4>
@if(!is_null($session) && $session->id === $user->id)
<a class="btn btn-primary" href="{{ url('user/auth/edit', ['id' => session('user.id')]) }}">
編輯資料
</a>
歡迎您
@else
您正在查看
@endif
{{ $user->name }}
</h4>
</div>
@foreach ($user->posts as $post)
<div class="list-group-item">
<p>
{{ $post->content }}
</p>
{{ $post->created_at }}
</div>
@endforeach
</div>
@stop
~~~
再次訪問 http://thinkphp.test/user/auth/read/id/1.html 即可看到前端內容完整的被渲染出來了。
- 第一章. 基礎信息
- 1.1 序言
- 1.2 關于作者
- 1.3 本書源碼
- 1.4 反饋糾錯
- 1.5 安全指南
- 1.6 捐助作者
- 第二章. 開發環境布置
- 2.1 編輯器選用
- 2.2 命令行工具
- 2.3 開發環境搭建
- 2.4 瀏覽器選擇
- 2.5 第一個應用
- 2.6 Git 工作流
- 第三章. 構建頁面
- 3.1 章節說明
- 3.2 靜態頁面
- 3.3 Think 命令
- 3.4 小結
- 第四章. 優化頁面
- 4.1 章節說明
- 4.2 樣式美化
- 4.3 局部視圖
- 4.4 路由鏈接
- 4.5 用戶注冊頁面
- 4.6 集中視圖
- 4.7 小結
- 第五章. 用戶模型
- 5.1 章節說明
- 5.2 數據庫遷移
- 5.3 查看數據表
- 5.4 模型文件
- 5.5 小結
- 第六章. 用戶注冊
- 6.1 章節說明
- 6.2 注冊表單
- 6.3 用戶數據驗證
- 6.4 注冊失敗錯誤信息
- 6.5 注冊成功
- 6.6 小結
- 第七章. 會話管理
- 7.1 章節說明
- 7.2 會話
- 7.3 用戶登錄
- 7.4 退出
- 7.5 小結
- 第八章. 用戶 CRUD
- 8.1 章節說明
- 8.2 重構代碼
- 8.3 更新用戶
- 8.4 權限系統
- 8.5 列出所有用戶
- 8.6 刪除用戶
- 8.7 訪客模式
- 8.8 優化前端
- 8.9 小結
- 第九章. 微博 CRUD
- 9.1 章節說明
- 9.2 微博模型
- 9.3 顯示微博
- 9.4 發布微博
- 9.5 微博數據流
- 9.6 刪除微博
- 9.7 小結