天天看點

php 關聯一對多 條數,關聯之一對多關聯

關聯之一對多關聯

一對多關聯

關聯定義

一對多關聯的情況也比較常見,使用hasMany方法定義,

參數包括:

hasMany('關聯模型名','外鍵名','主鍵名',['模型别名定義']);

例如一篇文章可以有多個評論

namespace appindexmodel;

use thinkModel;

class Article extends Model

{

public function comments()

{

return $this->hasMany('Comment');

}

}

同樣,也可以定義外鍵的名稱

namespace appindexmodel;

use thinkModel;

class Article extends Model

{

public function comments()

{

return $this->hasMany('Comment','art_id');

}

}

如果需要指定查詢字段,可以使用下面的方式:

namespace appindexmodel;

use thinkModel;

class Article extends Model

{

public function comments()

{

return $this->hasMany('Comment')->field('id,author,content');

}

}

關聯查詢

我們可以通過下面的方式擷取關聯資料

$article = Article::get(1);

// 擷取文章的所有評論

dump($article->comments);

// 也可以進行條件搜尋

dump($article->comments()->where('status',1)->select());

根據關聯條件查詢

可以根據關聯條件來查詢目前模型對象資料,例如:

// 查詢評論超過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'],

]);

定義相對的關聯

要在 Comment 模型定義相對應的關聯,可使用 belongsTo 方法:

name appindexmodel;

use thinkModel;

class Comment extends Model

{

public function article()

{

return $this->belongsTo('article');

}

}