sumit
sumit

Reputation: 15464

fetching primary keys from multiple records-laravel

I need to pull array of primary keys in single shot

i.e

select p_k from table where 1=1

result should be

$p_k=array(1,2,5,7)

i tried

$news = DB::table('news')

but for id i need to make a loop. isn't there a shortcut method via orm

my table is

id                   heading                 news
1                    heading1                news1
2                    heading2                news2 

I need list of id(primary key) in array like below

array(1,2)

$news = DB::table('news') will fecth all fields and furthermore i need to go through the loop

foreach($news as $val){
 $id[]=$val->id
}

This is quite lenghty.. i need a shortcut method so that i can directly pull those primary key on array with out loop

i need do to so because i have another bridge table where these news_id are linked

NewsTag::destroy($newsidarray);

Upvotes: 0

Views: 244

Answers (2)

The Alpha
The Alpha

Reputation: 146191

You may try this:

$news = News::lists('id');

Using your News model (Eloquent) with the combination of lists method.

Upvotes: 1

halkujabra
halkujabra

Reputation: 2942

$ids = DB::table('news')->lists('id');

This will do it. Reference is here-

http://laravel.com/docs/queries#selects

Upvotes: 2

Related Questions