Laravel,sync() - 如何同步数组并传递额外的数据透视字段?

问题描述 投票:45回答:5

官方的Laravel文档在sync()函数上有这个:

$user->roles()->sync( array( 1, 2, 3 ) );

您还可以将其他数据透视表值与给定ID相关联:

$user->roles()->sync( array( 1 => array( 'expires' => true ) ) );

在后一示例中,仅添加了一个枢轴行。我不明白的是,如果要同步多行,如何关联其他数据透视表记录?

提前致谢。

php laravel pivot eloquent sync
5个回答
104
投票

为了sync多个模型以及自定义数据透视数据,您需要:

$user->roles()->sync( array( 
    1 => array( 'expires' => true ),
    2 => array( 'expires' => false ),
    ...
));

IE浏览器。

sync( array( 
    related_id => array( 'pivot_field' => value ),
    ...
));

编辑

回答评论:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);

12
投票

这适合我

foreach ($photos_array as $photo) {

    //collect all inserted record IDs
    $photo_id_array[$photo->id] = ['type' => 'Offence'];  

}

//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false

1
投票

附加/分离

Eloquent还提供了一些额外的辅助方法,使相关模型的使用更加方便。例如,假设用户可以拥有多个角色,而角色可以拥有许多用户。要通过在连接模型的中间表中插入记录来将角色附加到用户,请使用attach方法:

$user = App\User::find(1);

$user->roles()->attach($roleId);

将关系附加到模型时,您还可以传递要插入到中间表中的其他数据数组:

$user->roles()->attach($roleId, ['expires' => $expires]);

如果要删除旧角色并且仅保留现在附加的新角色,也可以使用“同步”

$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires]);

可以通过传递'false'作为第二个参数来更改默认行为。这将使用ID 1,2,3附加角色,而不会影响现有角色。

在此模式下,sync行为与attach方法类似。

$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires], false);

参考:https://laravel.com/docs/5.4/eloquent-relationships


1
投票

将以下特征添加到项目中,并将其作为特征附加到模型类中。这很有用,因为这增加了使用多个枢轴的功能。可能有人可以清理一下并改进它;)

namespace App\Traits;

trait AppTraits
{
    /**
     * Create pivot array from given values
     *
     * @param array $entities
     * @param array $pivots
     * @return array combined $pivots
     */
    public function combinePivot($entities, $pivots = [])
    {
        // Set array
        $pivotArray = [];
        // Loop through all pivot attributes
        foreach ($pivots as $pivot => $value) {
            // Combine them to pivot array
            $pivotArray += [$pivot => $value];
        }
        // Get the total of arrays we need to fill
        $total = count($entities);
        // Make filler array
        $filler = array_fill(0, $total, $pivotArray);
        // Combine and return filler pivot array with data
        return array_combine($entities, $filler);
    }
}

模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use Traits\AppTraits;
    // ...
}

用法:

// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
    'price' => 634,
    'name'  => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);

0
投票

只需将字段及其值附加到元素:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);
© www.soinside.com 2019 - 2024. All rights reserved.