Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel与firstOrCreate多对多同步_Php_Laravel_Synchronization - Fatal编程技术网

Php Laravel与firstOrCreate多对多同步

Php Laravel与firstOrCreate多对多同步,php,laravel,synchronization,Php,Laravel,Synchronization,我曾经在多个下拉列表中选择我的标签,但我将其更改为一个文本字段,在该字段中我可以手动输入多个标签。然后,我只需先调用或创建方法,然后我想将它们同步到我的模型中,但我不知道如何做到这一点。到目前为止,我的代码是: // Here I simply create my new model $expense = auth()->user()->expenses()->create($request->all()); $tags = []; // For each enter

我曾经在多个下拉列表中选择我的标签,但我将其更改为一个文本字段,在该字段中我可以手动输入多个标签。然后,我只需先调用
或创建
方法,然后我想
将它们同步到我的模型中,但我不知道如何做到这一点。到目前为止,我的代码是:

// Here I simply create my new model
$expense = auth()->user()->expenses()->create($request->all());

$tags = [];

// For each entered tag I grab it from the database or I create it
foreach(explode(",", $request->tags) as $tag)
{
    $tags[] = auth()->user()->tags()->firstOrCreate(['name' => $tag]);
}

// Here is what I used to do, but I had an array of tag_ids
$expense->tags()->sync($tags);

不确定下一步要做什么,这也是我第一次使用
first或create
,因此,任何关于如何改进上述代码的指针都可能是非常受欢迎的。当然,我的主要问题是,如何将标记对象与我新创建的费用同步?

实际上非常简单,只需添加
->value('id')

$tags[] = auth()->user()->tags()->firstOrCreate(['name' => $tag])->value('id');