Laravel 5.5 中间表类型转换 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区

[Laravel 5.5 中间表类型转换 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区]

[file

](https://lccdn.phphub.org/uploads/images/201707/06/5350/x3GV4SGt4a.png)

Laravel 5.5 新增了向中间表模型插入或者更新数据时对类型转换的支持。

目前,在原来的模型中你可以用 $casts 来双向转换。任何继承 Eloquent\Model 类的模型都会查找 $casts 属性,并在读取和写入时将指定的属性转化为数据类型。例如,文档 里面有个例子:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
    * The attributes that should be cast to native types.
    * @var array
    */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

在 Laravel 5.4 中,Taylor 也在自定义中间表模型上添加了定义 $casts 属性的功能,但是只在读取数据时应用了 $casts ,而插入或更新属性时并不会执行转换。

例如,假设你有 Runner 赛跑者模型和 Race 比赛模型。 一个跑步者可以有很多比赛,一场比赛可以有很多赛跑者。 我们把中间表模型称为 RaceRunner,其中包括具有不同数量的单圈时间(取决于比赛的长度,以秒为单位)的 splits 数组,以及所需的 runner_idrace_id

splits 数组在 race_runner 表中以 JSON 格式序列化,因此如果你在 RaceRunner 中间表模型的 $casts 中将 splits 定义为数组,那 dd 出来的结果就会是数组:

dd( $runner->pivot->splits );

// Example:
[
    'Lap 1' => 150,
    'Lap 2' => 163,
    'Lap 3' => 146
]

只是,在创建或更新中间表模型时,你还是要手动转换:

// Cast first...
$splits = $splits->toJson();

// ...then attach:
$runner->races()->attach($raceId, ['splits' => $splits]);

现在,在 Laravel 5.5,Eloquent\ModelEloquent\Relations\Pivot 类的 $casts 属性都会 有一样的行为。 无论你是读取、插入还是更新数据,Laravel 都会「遵循」$casts 属性的设置。 也就是 attachsyncsave 方法也可用于中间表模型。 这个新功能会应用在上面的例子里,即 // Cast first … 后面这一步的代码将不再需要。

关于中间表 Pivot 的用法可以查看 文档, 更多的还有 Leo 大神Laravel 技巧之 Pivot :satisfied:

参考链接:https://laravel-news.com/laravel-5-5-pivot-casting

Stay Hungry, Stay Foolish.


Original url: Access

Created at: 2018-10-10 18:21:18

Category: default

Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论