【问题标题】:fetching primary keys from multiple records-laravel从多个记录中获取主键-laravel
【发布时间】:2014-06-04 05:24:14
【问题描述】:

我需要一次性提取主键数组

select p_k from table where 1=1

结果应该是

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

我试过了

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

但对于 id,我需要创建一个循环。是不是有通过 orm 的捷径方法

我的桌子是

id                   heading                 news
1                    heading1                news1
2                    heading2                news2 

我需要数组中的 id(主键)列表 如下所示

array(1,2)

$news = DB::table('news') 会影响所有字段,而且我需要遍历循环

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

这很长……我需要一个快捷方法,这样我就可以直接在数组上拉出那些主键而无需循环

我需要这样做,因为我有另一个桥接表,这些 news_id 链接在其中

NewsTag::destroy($newsidarray);

【问题讨论】:

  • 似乎解释不正确
  • 我已经编辑了我的问题..对不起
  • 您有news 表的News 模型吗?

标签: php mysql orm laravel eloquent


【解决方案1】:
$ids = DB::table('news')->lists('id');

这样就可以了。参考在这里-

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

【讨论】:

  • 谢谢 .. 这也有效.. 有时我们可能不需要模型.. 在投票之前必须有人考虑
  • @WereWolf-TheAlpha 为什么不看看我提供的文档链接?
  • $news = DB::table('category_news') ->whereIn('category_id', $data['categories'])->lists('id');像魅力一样工作
  • 糟糕!我的错,你没有打电话给get
  • 对不起!这是我的错,但+1 我没看到你没有打电话给get :-)
【解决方案2】:

你可以试试这个:

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

News 模型(Eloquent)与lists 方法结合使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2018-05-14
    • 2017-07-25
    • 1970-01-01
    • 2016-03-15
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多