我想把 "simplexml_load_file "附帶的一些資料保存到資料庫中,但它沒有保存,我想知道問題出在哪里?
我想保存的是 "US DOLLAR, EUR, POUND STERLING"
"message"。"Illuminate/Support/Facades/Date類的物件不能被轉換為字串"。
Route::post('/exchange_rates',[ToolsController::class, 'kurlar'])。)
Schema:: create(' exchanges', function (Blueprint $table) {
$table->id()。
$table->boolean('buying_rate')。
$table->boolean('selling_rate')。
$table->date('date')。
$table->string('currency')。
$table->timestamps()。
})
public function kurlar()
{
$products = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml'/span>);
$pred = [0, 3, 4] 。
print_r($products)。
foreach ($products as $product) {
$exchange = new Exchange;
$exchange-> buying_rate = $product->ForexBuying;
$exchange->selling_rate = $product->ForexSelling;
$exchange->date = new Date();$product->屬性['Date']。
$exchange->currency = $product-> attributes['CurrencyCode'];
$exchange->save()。
}
uj5u.com熱心網友回復:
首先是錯誤。IlluminateSupportFacadesDate類的物件不能被轉換為字串意味著你不能通過傳遞一個new Date()物件在模型中保存一個日期屬性, 對于簡單的Laravel允許你只是把日期作為一個字串傳遞到所需的屬性。
在實施和修改你的代碼后, 我得到了這個作業版本:
在實施和修改你的代碼后, 我得到了這個作業版本:
public function kurlar(){
$products = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml'/span>);
$exchanges = [];
foreach ($products as $product) {
$exchange = new Exchange;
$exchange->buying_rate = get_object_vars($product->ForexBuying)[0] 。
$exchange->selling_rate = get_object_vars($product->ForexSelling) [0] ? 0; /0 as default value when returning null from ForexSelling?
//'2021-09-19'作為默認日期,因為所有產品的資料都回傳空值。
$exchange->date = '2021-09-19'/span>;
$exchange->currency = get_object_vars($product->attribute()['CurrencyCode']) [0] 。
if(in_array($exchange->currency, ['USD'/span>, 'EUR'/span>, 'GBP'/span>]){
$exchange-> save();
array_push($exchanges, $exchange) 。
}
}
return $exchanges;
}
或者,你可以通過使用for回圈來檢查索引:
for ($i=0; $i < count($products-> Currency) ; $i ) {
$product = $products->Currency[$i] 。
# code...
$exchange = new Exchange;
$exchange->buying_rate = get_object_vars($product->ForexBuying)[0] 。
$exchange->selling_rate = get_object_vars($product->ForexSelling) [0] ? 0; /0 as default value when returning null from ForexSelling?
//'2021-09-19'作為默認日期,因為所有產品的資料都回傳空值。
$exchange->date = '2021-09-19'/span>;
$exchange->currency = get_object_vars($product->attribute()['CurrencyCode']) [0] 。
if(in_array($i, [0, 3, 4]){
$exchange-> save();
array_push($exchanges, $exchange) 。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/324243.html
標籤:
