關於thinkphp6中使用了field()將導致模型關聯查找不到數據解決方案


案例回放

需求:我只要取profile中的某些字段進行進一步操作。

我們查詢到了資料表

$profile = Profile::where('user_id', session('index_user_id'))->field(['avatar','nickname','bio'])->find();

Profile模型中有定義一個一對一的關聯關系

    public function old()
    {
        return $this->hasOne(ProfileOld::class);
    }

查看關聯數據

 dd($profile->old);

結果是 null

解決方案

使用hidden、visible和append 來對結果集進行控制

//查詢出老的資料數據
$profile = Profile::where('user_id', session('index_user_id'))->find();


$needArr = $profile->visible(['avatar','nickname','bio'])->toArray();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM