pl (評論) - uid, contentuser (用戶) - id, usernamelyb (留言板) - uid, titleclass PlViewModel extends ViewModel {
public $viewFields = [
'pl' => ['uid', 'rid', 'content'],
'user'=> ['id', 'username', '_on' => 'pl.uid=user.id'],
'lyb' => ['uid'=>'lid', 'content'=>'lyb_content', 'title', '_on' => 'pl.uid=lyb.uid'],
];
}
控制器調用:
$list = D('PlView')->field('uid,title,username,lyb_content')->select();
// 若有重複資料:->group('pl.uid')
$list = D('pl')
->join('lyb ON pl.uid = lyb.uid')
->join('user ON pl.uid = user.id')
->field('user.username, lyb.title, pl.content')
->select();
JOIN 類型:INNER JOIN (預設)、LEFT JOIN、RIGHT JOIN、FULL JOIN,可在 join() 字串指定。
$list = D('pl')
->field('pl.content, user.username, lyb.title')
->table('pl, lyb, user')
->where('pl.uid=user.id AND pl.uid=lyb.uid') // 必須手寫 WHERE 關聯條件
->limit(10)
->select();
注意:table() 預設查所有欄位,需用 field() 限制,且需自行寫關聯條件,易出錯。
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| ViewModel | 定義一次複用、自動處理關聯、支援關聯預載入 | 需建立模型類別 | 固定關聯、常用查詢、專案中大型報表 |
| JOIN | 靈活、SQL 可見、支援各種 JOIN 類型 | 複雜關聯 SQL 字串長、欄位衝突需別名 | 臨時查詢、動態關聯條件 |
| table() | 簡單、無需模型 | 手寫 WHERE 易錯、不支援關聯預載入 | 極簡單雙表、快速原型 |
// 模型定義關聯
class PlModel extends Model {
protected $_link = [
'user' => ['mapping_type' => BELONGS_TO, 'foreign_key' => 'uid', 'mapping_fields' => 'username'],
'lyb' => ['mapping_type' => BELONGS_TO, 'foreign_key' => 'uid', 'mapping_fields' => 'title'],
];
}
// 控制器
$list = D('Pl')->relation(true)->select(); // 自動帶入 user、lyb 關聯資料