简体   繁体   English

Laravel 关系 hasMany updateOrCreate 数组

[英]Laravel relationships hasMany updateOrCreate array

I have User model which has relationships hasMany with UserPosition eloquent model:我有User模型,它与hasManyUserPosition eloquent 模型有关系:

User model用户模型

public function positions()
{
    return $this->hasMany(UserPosition::class);
}

How I can use updateOrCreate method when from request come array of data positions?当来自请求的数据位置array时,如何使用updateOrCreate方法?

Code代码

$positions = [
    "doctor",
    "developer"
];

$user->positions()->each(function($position) use ($positions, $user) {
    $id = $user->id;
    foreach ($positions as $name) {
        $position->updateOrCreate(['user_id' => $id, 'name' => $name], [
            'name' => $name
        ]);
    }
});

Note: In this example user doesn't has any positions on the table of database注意:在这个例子中,用户在数据库表上没有任何位置

But my code not work.但我的代码不起作用。 Why?为什么?

You are iterating on the existing positions of a user, meaning that if a user has no positions the iteration will never happen.您正在迭代用户的现有职位,这意味着如果用户没有职位,则迭代将永远不会发生。 You can iterate along the positions you need to make:您可以沿着您需要的位置进行迭代:

$positions = collect([
    "doctor",
    "developer"
]);

$positions->each(function($position) use ($user) {
        $user->positions()->updateOrCreate(['name' => $position], [
            'name' => $position
        ]);
    }
});

It doesn't work because your running your updateOrCreate() method inside an each iteration which never runs because as you stated in your note "this example user doesn't has any positions on the table of database"它不起作用,因为您在每次迭代中运行updateOrCreate()方法,该方法从未运行,因为正如您在注释中所述“此示例用户在数据库表上没有任何位置”

Here your trying to loop through your currently existing positions attached to your user model:在这里,您尝试遍历附加到用户模型的当前现有职位:

$user->positions()->each()

But that won't run because the user doesn't have any positions at the moment.但这不会运行,因为用户目前没有任何职位。

I'm guessing you are trying to update the the user's positions, where it is possible that the user already has one or more of those positions associated to him and you don't want to create duplicates, for that you can do this:我猜您正在尝试更新用户的职位,在这种情况下,用户可能已经拥有一个或多个与他相关的职位,并且您不想创建重复项,为此您可以这样做:

$positions = [
    "doctor",
    "developer"
];

foreach($positions as $position) {
    UserPosition::firstOrCreate(['user_id' => $user->id, 'name' => $position]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM