模型一對多

建立模型Users

namespace app\admin\model;
use \think\Model;
class Users extends Model
{
     // 建立關(guān)聯(lián)屬性
     public function comments()
    {
          return $this->hasOne("comments","uid");
    }
}

建立模型Comments

  namespace app\admin\model;
  use \think\Model;
  class Comments extends Model
  {

  }

控制器代碼

單個數(shù)據(jù)獲取

    $users = new Users();
    $data = $users->where("mobilenum",'1875251xxxx')->find();
    $comments = $user->comments()->where("isshow",1)->select();//獲取該用戶所有通過審核的評論
    print_r($comments);

多個數(shù)據(jù)

    $users = new Users();
    $users = Users::all(function($query){
        $query->where("ischeack='0'");
    });// 閉包查詢 未通過審核的所有用戶
    foreach ($users as $key=>$user)
    {
        $user->comments;
        print_r($user->toArray());
    }

關(guān)聯(lián)操作也可以用“getBy字段名”的方法

$comments = $user->comments()->getByContents("這個文章不錯");
//所生成的sql語句為
select * from hc_comments where uid=2 and contents='這個文章不錯';

 // 查詢所有評論過的用戶
$user = Users::has("comments")->select();
// 查詢評論過兩次以上的用戶信息
$user = Users::has("comments",">=",2)->select();
// 評論內(nèi)容是”這個文章不錯“的所有用戶信息
$user = Users::hasWhere("comments",["contents"=>"這個文章不錯"])->select();

關(guān)聯(lián)更新

$user = Users::get(1);
$comments = $user->comments()->getByCotents("這個文章不錯");
$comments->contents = '這里是更新過的內(nèi)容';
$comments->save();

也可以使用構(gòu)造器更新

$user =Users::get(1);
$user->comments()->where("id",1)->update(["contents"=>"這里是更新過的內(nèi)容"]);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容