Laravel Collection无法正常工作

时间:2016-07-02 05:46:45

标签: php laravel collections

我的收藏有问题

 $tasks = Bear::all();
 $val = new Collection([]);
 foreach($tasks as $tas){
     $val ->push($tas->id);
 }

 $tasks1 = BearPic::whereIn('bear_id',$val)->get();
 $val2 = new Collection([]);
 foreach($tasks1 as $tas){
     $val ->push($tas->bear_id);
 }

我对val的回应是

[10,11,12,10,10,11,11,12,12]

tasks1

[{
    "id": 1,
    "bear_id": 10,
    "picnic_id": 1,
    "created_at": null,
    "updated_at": null
}, {
    "id": 2,
    "bear_id": 10,
    "picnic_id": 2,
    "created_at": null,
    "updated_at": null
}, {
    "id": 3,
    "bear_id": 11,
    "picnic_id": 1,
    "created_at": null,
    "updated_at": null
}, {
    "id": 4,
    "bear_id": 11,
    "picnic_id": 2,
    "created_at": null,
    "updated_at": null
}, {
    "id": 5,
    "bear_id": 12,
    "picnic_id": 1,
    "created_at": null,
    "updated_at": null
}, {
    "id": 6,
    "bear_id": 12,
    "picnic_id": 2,
    "created_at": null,
    "updated_at": null
}]

第二个集合返回空 可能是什么问题?我对laravel很新,这是一个教程

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望将$val2集合的所有$tasks1 = BearPic::whereIn('bear_id',$val)->get(); $val2 = $tasks1->pluck('id'); 值都设置为$userID = the_author_meta( 'ID' ); if ($userID!= 0) //0 is for admin author id { get_the_author_meta( '/*what ever you want to get */' ) } else { //The else part for the default admin author. } ,我是否正确?如果是这样,你可以这样做:

a <- as.numeric(as.character(a))

答案 1 :(得分:0)

第二个集合val2是空的,因为您将值推送到val,即第一个集合而不是val2

此外,如果您坚持不使用联接和处理集合,pluck确实是一个更快的解决方案。

$tasks = Bear::all();
$val = $tasks->pluck('id');

$tasks1 = BearPic::whereIn('bear_id', $val)->get();
$val2 = $tasks2->pluck('bear_id');