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.

enter image description here

here's what's happening:

  1. with ->first() actual project model

  2. then call pluck('id') on it. model class doesn't have method.

  3. so with, every method model doesn't know, redirects call new query builder instance of model.

  4. 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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -