class ModelTableSeeder extends Seeder {
public function run()
{
DB::table('models')->delete();
$now = date('Y-m-d H:i:s');
$records = [
['Echo', 'Toyota']
];
for($i = 0; $i < count($records); $i++)
{
DB::table('models')->insert(
array(
'name' => $records[$i][0],
'manufacturer_id' => DB::table('manufacturers')->where('name', '=', $records[$i][1])->get('id'),
'created_at' => $now,
'updated_at' => $now
)
);
}
}
}
That's not working either.
Hi,
I think the problem is the way you use the get method. It's argument should be an array: https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Query/Builder.php#L1332
So, try
$records = [
['Echo', DB::table('manufacturers')->where('name', '=', 'Toyota')->get(['id'])]
];
Oh THAT's what the error's referring to! Brilliant thank you
Could definitely have a nicer error message there :)
Ok unfortunately it's still not quite working when I specify id as an array element.
<?php
class ModelTableSeeder extends Seeder {
public function run()
{
DB::table('models')->delete();
$records = [
['Echo', 'Toyota']
];
for($i = 0; $i < count($records); $i++)
{
$manufacturer_id = DB::table('manufacturers')->where('name', '=', $records[$i][1])->get(['id']);
DB::table('models')->insert(
array(
'name' => $records[$i][0],
'manufacturer_id' => $manufacturer_id,
'created_at' => new DateTime,
'updated_at' => new DateTime
)
);
}
}
}
I get this error:
"preg_replace(): Parameter mismatch, pattern is a string while replacement is an array." :(
$records = [['Echo', 'Toyota']];
$manufacturer_id = DB::table('manufacturers')
->where('name', '=', $records[0][1])
->get(['id']);
var_dump($manufacturer_id);
This gives an stdClass and I need to fetch the ID value and convert it to a string. How do I do that? Here's the output:
array (size=1)
0 =>
object(stdClass)[158]
public 'id' => int 2
What I ended up with:
public function run()
{
DB::table('models')->delete();
$records = [
['Echo', 'Toyota']
];
for($i = 0; $i < count($records); $i++)
{
$manufacturer = DB::table('manufacturers')
->where('name', '=', $records[$i][1])
->select('id')->first();
DB::table('models')->insert(
array(
'name' => $records[$i][0],
'manufacturer_id' => $manufacturer->id,
'created_at' => new DateTime,
'updated_at' => new DateTime
)
);
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community