在laravel集合对象中添加新元素

时间:2015-11-20 14:10:01

标签: php laravel-5 laravel-5.1

我想在$ items数组中添加新元素,我不想出于某些原因使用连接。

$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
        foreach($items as $item){
            $product = DB::select(DB::raw(' select * from product
                   where product_id = '. $id.';' ));

            $item->push($product);
        }

我应该怎么做,请提前帮助,thnx

5 个答案:

答案 0 :(得分:72)

看起来你有一切正确according to Laravel docs,但你有一个错字

$item->push($product);

应该是

$items->push($product);

我还想认为您正在寻找的实际方法是put

$items->put('products', $product);

答案 1 :(得分:4)

如果要将项目添加到集合的开头,可以使用 prepend:

$item->prepend($product, 'key');

答案 2 :(得分:2)

如上所述,如果您希望将查询的集合用作新元素,则可以使用:

After the tombstones pass the gc_grace_seconds they will be ignored in result sets because they are 
filtered out after they have past that point. So you are correct in the assumption that the only way for the 
tombstone warning to post would be for the data to be past their ttl but still within gc_grace.


And since they are ignored/filtered out they wont have any harmful effect 
on the system since like you said they are skipped.

但是,如果您希望向每个查询的元素添加新元素,则需要这样做:

import { Model, PartitionKey, DynamoStore } from '@shiftcoders/dynamo-easy'

@Model()
export class Person {
  @PartitionKey()
  id: string
  name: string
  yearOfBirth: number
}

const personStore = new DynamoStore(Person)

personStore
  .scan()
  .whereAttribute('yearOfBirth').equals(1958)
  .exec()
  .then(res => console.log('ALL items with yearOfBirth == 1958', res))

add_whatever_element_you_want可以是您希望元素名称像产品一样的

答案 3 :(得分:1)

如果要将产品添加到数组中,可以使用:

$item['product'] = $product;

答案 4 :(得分:0)

如果您使用的是2个表的数组,我已经解决了。你有例子 $tableA['yellow']$tableA['blue']。您将获得这2个值,并且想要在其中添加另一个元素,以通过其type分隔它们。

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

因此,两个表的值都将有一个名为type的新元素。