2 回答

TA貢獻1836條經驗 獲得超4個贊
關系
在Wallet模型中建立關系
class Wallet extends Model
{
public function walletcategory()
{
return $this->belongsTo('App\Wallet_Category','wallet_category_id','id');
}
}
現在在控制器中
$wallets = Wallet::with('walletcategory')->where('user_id', $request->get('user_id'))->get();
foreach($wallets as $wallet){
$wallet->walletcategory->name
}
加入
如果您想通過使用 join 來獲取它,請按照以下查詢。
Wallet::select('wallet.*','wallet_category.name')->leftjoin('wallet_category','wallet_category.id','wallet.wallet_category_id')->where('wallet.user_id', $request->get('user_id'))->get();

TA貢獻1803條經驗 獲得超6個贊
一種方法是在檢索錢包時使用Eagar 加載 錢包類別關系信息
在錢包模型中創建關系
//Wallet.php
...
use App\Wallet_Category;
...
public function walletCategory(){
return $this->belongsTo(Wallet_Category, 'wallet_category_id', 'id')
}
現在從關系中檢索必要的列,如 id、name
$wallets = Wallet::with('walletCategory:id,name')->where('user_id', $request->get('user_id'))->get();
您將能夠檢索 walletCategory 名稱,例如:
foreach($wallets as $wallet){
//retrieve wallet category name like
$wallet->walletCategory->name
}
- 2 回答
- 0 關注
- 169 瀏覽
添加回答
舉報