簡體   English   中英

使用兩個查詢或使用關系在兩個表上插入數據

[英]Using two queries or using relation to insert data on two tables

我有兩個表,一個是“用戶”,另一個是“錢包”。 錢包表與用戶表關聯為“ hasOne”。 所以我有一個需要更新用戶表和錢包表的場景。

但是問題是,我只有hasOne與用戶相關的錢包。 而且我不知道我在做什么,我的方法還是不好的。 實際上是分別為用戶和錢包查詢兩次。

因此,從代碼開始,首先是查詢用戶以增加計數,然后再次查詢錢包以執行其他查詢。 這有效嗎? 或者我可以將“ belongsTo”從錢包關聯到用戶,以便在單個查詢中完成所有操作?

請指導我最好的方法。

$level_count = User::findOrFail($h)->increment('level_count', 1);
$wallet = Wallet::where('user_id', $h)->first();
$wallet->increment('wallet_balance',200);
$wallet->wallet_logs()->create(['wallet_logs' => 'Commission INR 200 
Credited']);

現在,您的代碼將執行以下語句(如非常有用的Laravel Debugbar所示 ):

select * from `users` where `users`.`id` = 1 limit 1
update `users` set `level_count` = `level_count` + 1, `users`.`updated_at` = '2019-07-25 14:05:44' where `id` = 1
select * from `wallets` where `user_id` = 1 limit 1
update `wallets` set `wallet_balance` = `wallet_balance` + 200, `wallets`.`updated_at` = '2019-07-25 14:05:44' where `id` = 1
insert into `wallet_logs` (`wallet_logs`, `wallet_id`, `updated_at`, `created_at`) values ('Commission INR 200 \r\n     Credited', 1, '2019-07-25 14:05:44', '2019-07-25 14:05:44')

哪個可行,但由於用戶和電子錢包之間未使用任何關系,因此代碼不是很整齊。 我將其重寫為:

$user = User::with('wallet')->find($h);
$user->increment('level_count', 1);
$user->wallet->increment('wallet_balance', 200);
$user->wallet->wallet_logs()->create(['wallet_logs' => 'Commission INR 200 Credited']);

User.php中將需要此關系:

public function wallet()
{
    return $this->hasOne('App\Wallet');
}

但是,這不會執行更少的查詢。 除非您願意使用查詢生成器使用JOIN構造(相對復雜的)UPDATE查詢,否則查詢將不會減少。

我不擔心查詢的數量,因為它們非常簡單且快速,除非您期望有大量的請求。


編輯:實際上,可以減少用於更新的查詢數量,但是由於無論如何您都必須檢索電子錢包(以檢索其ID以寫入電子錢包日志),因此並沒有太大幫助。 這僅執行兩個UPDATE語句:

User::where('id', $h)->increment('level_count', 1);
Wallet::where('user_id', $h)->increment('wallet_balance', 200);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM