### ORM 數據庫
請充分理解關聯關系中的
## 一對一關聯 (hasOne)
<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid'); //uid是外鍵
}
}
## 一對一關聯 (從屬belongsTo)
<?php
name app\index\model;
use think\Model;
class Comment extends Model
{
public function article()
{
return $this->belongsTo('article');
}
}
## 關聯刪除
$article = Article::get(1,'comments');
$article->together('comments')->delete();
## 一對多關聯
例如一篇文章可以有多個評論
<?php
namespace app\index\model;
use think\Model;
class Article extends Model
{
public function comments()
{
return $this->hasMany('Comment');
}
}
同樣,也可以定義外鍵的名稱
<?php
namespace app\index\model;
use think\Model;
class Article extends Model
{
public function comments()
{
return $this->hasMany('Comment','art_id');
}
}
根據關聯條件查詢
查詢評論超過3個的文章
$list = Article::has('comments','>',3)->select();
查詢評論狀態正常的文章
$list = Article::hasWhere('comments',['status'=>1])->select();
關聯新增
$article = Article::find(1);
增加一個關聯數據
$article->comments()->save(['content'=>'test']);
批量增加關聯數據
$article->comments()->saveAll([
['content'=>'thinkphp'],
['content'=>'onethink'],
]);
關聯查詢
我們可以通過下面的方式獲取關聯數據
$article = Article::get(1);
獲取文章的所有評論
dump($article->comments);
也可以進行條件搜索
dump($article->comments()->where('status',1)->select());
關聯關系對照
類型 |關聯關系 |相對的關聯關系
-|-|-
一對一| hasOne| belongsTo
一對多 |hasMany |belongsTo
多對多| belongsToMany |belongsToMany
遠程一對多 |hasManyThrough |不支持
多態一對一 |morphOne |morphTo
多態一對多 |morphMany |morphTo
理解關聯關系,有助于快速開發系統功能。
禁止直接使用DB底層直接操作數據庫。
只可以使用model層。方便以后分表分庫操作,日志記錄等。
例如,Profile模型中就可以定義一個相對的關聯關系。
<?php
namespace app\index\model;
use think\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
在進行關聯查詢的時候,也是類似,只是當前模型不同。
獲取檔案實例
$profile = Profile::get(1);
獲取檔案所屬的用戶名稱
echo $profile->user->name;
如果你需要對關聯模型進行更多的查詢約束,可以在關聯方法的定義方法后面追加額外的查詢鏈式方法(但切忌不要濫用,并且不要使用實際的查詢方法),例如:
<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
public function book()
{
return $this->hasMany('Book')->order('pub_time');
}
}
更多關聯請查[手冊](http://www.hmoore.net/manual/thinkphp5_1/354056)