我對 Laravel 和后端非常陌生,所以我在這里迷路了。我需要遍歷表中的所有行并根據條件編輯欄位的資料。
該欄位由一個 url 組成,我想在開頭添加 http。我已經擁有該功能,但我無法撰寫遷移以遍歷所有欄位。任何人都可以幫忙嗎?
我想我主要是在訪問這里的表時遇到了問題。
public function up()
{
Schema::table('firms', function (Blueprint $table) {
$results = $table::where()->select('url')->get();
foreach ($results as $urls) {
$start = parse_url($urls->url, PHP_URL_SCHEME);
if ($start !== 'http' && $start !== 'https') {
$url = 'http://'.$urls->url;
DB::table('firms')->where('url', $url)->update(['url' => $url]);
}
if ($start === 'http' || $start === 'https') {
continue;
}
}
});
}
uj5u.com熱心網友回復:
你可以這樣做:
如果您有 Firm 模型:
// looping only to firms which url field is not starting with http
foreach(Firm::where('field', 'value')->where('url', 'not like', 'http%')->get() as $firm){
//updating single firm adding http://
$firm->update(['url' => 'http://' . $firm->url]);
}
//or in just one line:
Firm::where('url', 'not like', 'http%')->update(['url' => DB::raw("CONCAT('http://', url)")]);
在這種情況下where('field', 'value')是可選的其他條件,您可以將其洗掉。
第一個解決方案更新 updated_at 欄位,第二個不
如果您沒有 Firm 型號:
DB:raw("Update firms set url = CONCAT('http://', url) where url not like 'http%'");
正如@brombeer 指出的那樣,在工匠命令中執行要干凈得多
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399641.html
下一篇:一項在資料庫中應用多項更改的請求
