How can I convert stdClass to Arra开发者_如何学Pythony to update my DB in Laravel?
$currentSubscriptionTransaction = new stdClass();
$subscription_transaction_to_update = DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->first();
if (!is_null($subscription_transaction_to_update)) {
DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->update(
($currentSubscriptionTransaction)
);
}
I tried
array($currentSubscriptionTransaction)
but it didn't work.
Try this:
$subscription_transaction_to_update = DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->first();
if (!is_null($subscription_transaction_to_update)) {
DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->update(
($currentSubscriptionTransaction->toArray()) // this has to be an array
);
}
A cleaner way of doing the same by using Eloquent Model
SubscriptionTransaction::firstOrCreate($currentSubscriptionTransaction->toArray());
humm...
Maybe, you should better use some helper functions
like collect()
and toArray()
?
see https://readouble.com/laravel/5.7/en/helpers.html if your laravel version is 5.7
Laravel supply some useful methods or tips belong with your laravel app version.
For example if you use a DB table , this framework has model.php like SubscriptionTransactions
under Models/
So,Can you try these code under following?
use App\Models\SubscriptionTransaction;
$subscriptionTransactionToUpdate = SubscriptionTransaction::firstWhere('id', $currentSubscriptionTransaction->id);
if ($subscriptionTransactionToUpdate) {
$currentSubscriptionTransaction = new stdClass();
$subscriptionTransactionToUpdate->update(collect($currentSubscriptionTransaction)->toArray());
}
精彩评论