Laravel 迁移以编辑现有 table 数据
Laravel migration to edit existing table data
我对 Laravel 和后端非常陌生,所以我在这里迷路了。
我需要遍历 table 中的所有行并根据条件编辑字段的数据。
该字段由一个url组成,我想在开头添加http。我已经有了那个功能,但我无法编写迁移来遍历所有字段。有人可以帮忙吗?
我想我主要是无法访问此处的 table。
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;
}
}
});
}
你可以这样做:
如果您有公司型号:
// 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 字段,第二个不更新
如果您没有公司型号:
DB:raw("Update firms set url = CONCAT('http://', url) where url not like 'http%'");
正如@brombeer 指出的那样,用 artisan 命令来做会更简洁
我对 Laravel 和后端非常陌生,所以我在这里迷路了。 我需要遍历 table 中的所有行并根据条件编辑字段的数据。
该字段由一个url组成,我想在开头添加http。我已经有了那个功能,但我无法编写迁移来遍历所有字段。有人可以帮忙吗?
我想我主要是无法访问此处的 table。
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;
}
}
});
}
你可以这样做:
如果您有公司型号:
// 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 字段,第二个不更新
如果您没有公司型号:
DB:raw("Update firms set url = CONCAT('http://', url) where url not like 'http%'");
正如@brombeer 指出的那样,用 artisan 命令来做会更简洁