简体   繁体   English

如何使用Laravel重写记录集中的值?

[英]How to rewrite a value in a record set with Laravel?

For example, this way get Photo records: 例如,通过这种方式获取Photo记录:

return DB::table('photos')->skip(1)->take(2)->get();

Return these data: 返回这些数据:

+----+--------+------------+
| id |  name  |   photo    |
|----|--------|------------|
| 1  | flower | flower.jpg |
| 2  | grass  | grass.jpg  |
...

Want to rewrite photo column data as this record set: 想要将photo列数据重写为此记录集:

+----+--------+------------------------------+
| id |  name  |          photo               |
|----|--------|------------------------------|
| 1  | flower |  https://my-site/flower.jpg  |
| 2  | grass  |  https://my-site/grass.jpg   |
...

Is there a simple way to do? 有简单的方法吗?

使用CONCAT方法:

DB::table('photos')->select('id','name',DB::raw("CONCAT('https://my-site/', 'photo') as photo")->skip(1)->take(2)->get();

You could make use of Accessor 你可以利用Accessor

Define this method in your Photo model 在您的Photo模型中定义此方法

/**
 * Get the photo's path.
 *
 * @param  string  $value
 * @return string
 */
public function getPhotoAttribute($value)
{
    return asset($value);
}

then you could try 那你可以尝试

return Photo::skip(1)->take(2)->get();

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

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