artisan - Laravel collection pluck method not working as expected -
i've entered fantastic world of laravel , looking seeding database fake data testing.
i have couple of tables want work with; projects , stories.
the stories table has columns; id, name , project_id (which fk projects table).
my projects table populated list of 10 projects. need populate 100 stories random projects associated. have approach below.
public function run() { db::table('stories')->delete(); db::statement('alter table stories auto_increment = 1'); $faker = faker::create(); foreach(range(1, 100) $index) { story::create([ 'reference' => $faker->numberbetween(1, 9999), 'name' => $faker->sentence(6), 'project_id' => project::orderby(\db::raw('rand()'))->get()->first()->pluck('id') ]); } }
i don't know if best way of doing need. however, when performing code every story's project_id set 1; first project's id.
when perform following command in tinker... returns 1 id.
project::orderby(\db::raw('rand()'))->get()->first()->pluck('id')
but when perform next command in tinker...
project::orderby(\db::raw('rand()'))->get()->first()
it returns random project every time. strange. because if ->pluck() working pluck() should fetch collected items id... right? above command returns.
<app\project #000000000c385908000000000de30942> { id: 6, name: "new bernadetteton", cover_photo_url: "/uploads/covers/horizon-grass.png", created_at: "2015-07-08 16:32:15", updated_at: "2015-07-08 16:32:15" }
see below screenshot terminal window illustrate mean.
here's what's happening:
with
->first()
actual project modelthen call
pluck('id')
on it.model
class doesn't have method.so with, every method
model
doesn't know, redirects call new query builder instance of model.in end, call ends here:
illuminate\database\eloquent\builder@value
public function value($column) { $result = $this->first(array($column)); if ($result) return $result->{$column}; }
as can see, method runs new query, using first()
, returns desired row.
now want either:
1. don't use pluck
@ all
there isn't need use method, can access model property:
'project_id' => project::orderby(\db::raw('rand()'))->first()->id
2. use pluck
, right
'project_id' => project::orderby(\db::raw('rand()'))->pluck('id')
and btw, main method called value()
. pluck()
alias. recommend using value()
in new code. it's possible alias removed day. (obviously in new release , note in upgrade guide, don't panic ;))
Comments
Post a Comment