G
G
ganjo8882019-08-13 19:54:35
Laravel
ganjo888, 2019-08-13 19:54:35

How to use updateOrCreate?

There is an array with screenshots

[ 
     {
        "url": "http://asd.ru/qwe.jpg",
        "uploaded": "true"
     },
 {
        "url": "http://asdas.ru/qwe.jpg",
        "uploaded": "true"
     }
  ]

you need to go through the array and update if there is such a url or create if not. At the same time, not all columns are displayed, but only certain ones ('episode_id', 'content', 'meta').
I do so
$array = [];
foreach ($params['screenshots'] as $screenshot) {
    $array[] = Material::updateOrCreate([
        'content' => $screenshot['url'],
    ], [
        'episode_id' => $params['episode_id'],
        'type_id'    => 2,
        'profile_id' => 2,
        'content'    => $screenshot['url'],
        'meta'       => true,
    ])->select(['episode_id', 'content', 'meta'])->get();
}

return $array;

I get duplicate results
{
  "jsonrpc": "2.0",
  "id": 10,
  "result": [
    [
      {
        "episode_id": 1,
        "content": "http:\/\/asd.ru\/qwe.jpg",
        "meta": true
      },
      {
        "episode_id": 1,
        "content": "123.jpg",
        "meta": true
      }
    ],
    [
      {
        "episode_id": 1,
        "content": "http:\/\/asd.ru\/qwe.jpg",
        "meta": true
      },
      {
        "episode_id": 1,
        "content": "123.jpg",
        "meta": true
      }
    ]
  ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Razgelday, 2019-08-19
@ganjo888

Try like this:

// ...

    $array[] = Material::updateOrCreate([
        'content' => $screenshot['url'],
    ], [
        'episode_id' => $params['episode_id'],
        'type_id'    => 2,
        'profile_id' => 2,
        'content'    => $screenshot['url'],
        'meta'       => true,
    ])->only(['episode_id', 'content', 'meta']); // Используем коллекции

// ...

updateOrCreate returns an object instance, which means that collection methods (Laravel Collections) can be applied to it - in this case, the only method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question