简体   繁体   English

Laravel Pluck Concat 关系

[英]Laravel Pluck Concat Relations

Im using laravel 8 to my project, trying to pluck data from a Model我在我的项目中使用 laravel 8,试图从模型中提取数据

    $user = Users::with('media')->get()->pluck('media.title', 'id')->all();

I got the Output我得到了输出

    {
     "sample": 1,
    }

My expected output,Looking for the value combine a column from media table and column from user table我的预期输出,寻找组合媒体表中的列和用户表中的列的值

   {
     "media.title + user.name": id,
   }

To my knowledge this isn't possible with pluck directly.据我所知,直接使用 pluck 是不可能的。 You have 2-3 options the way I see it:按照我的看法,您有 2-3 个选项:

Either make an accessor in your User model which concatenates the user name and the media title, something like:在您的User模型中创建一个连接用户名和媒体标题的访问器,例如:

public function getNameWithMediaAttribute()
{
    return $this->name . ' + ' . $this->media->title
}

Which you then pluck with ->pluck('nameWithMedia') after your query.然后在查询后使用->pluck('nameWithMedia')进行选择。


Or you can pull them the way you did with $user = Users::with('media')->get();或者你可以像$user = Users::with('media')->get();那样拉它们$user = Users::with('media')->get(); and map over the result to return the format you want.并映射结果以返回您想要的格式。 Something like:就像是:

$users = User::with('media')->get()->map(function($user) 
{
    return [$user->media->title . ' + ' . $user->name => $user->id];
})->collapse();

Don't forget about the ->collapse() part.不要忘记->collapse()部分。


You could also make a query which gathers that data under one field and then you pluck it after pulling it from the database.您还可以进行一个查询,在一个字段下收集该数据,然后在从数据库中提取它后提取它。 But my SQL-fu isn't good enough to do that easily.但是我的 SQL-fu 不够好,无法轻松做到这一点。

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

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