我的社交表控制器输出以下内容:
[
{
"id": 4,
"value": "FaAlgolia",
"name": "zaefzaef",
"profile_id": 4,
"order": 9000,
"created_at": "2021-05-17 20:25:03",
"updated_at": "2021-05-17 20:25:03"
},
{
"id": 5,
"value": "FaAlipay",
"name": "azdadzzad",
"profile_id": 4,
"order": 9000,
"created_at": "2021-05-17 20:41:53",
"updated_at": "2021-05-17 20:41:53"
}
]
这些元素中的每一个属于一个配置文件。
配置文件表:
社交表格:
在 profiles 表中,我有一个 URL 列。我想在我的数组中返回它,以便输出看起来像这样。
[
{
"id": 4,
"value": "FaAlgolia",
"name": "zaefzaef",
"profile_id": 4,
"order": 9000,
"created_at": "2021-05-17 20:25:03",
"updated_at": "2021-05-17 20:25:03"
"url": the url from profiles table
},
{
"id": 5,
"value": "FaAlipay",
"name": "azdadzzad",
"profile_id": 4,
"order": 9000,
"created_at": "2021-05-17 20:41:53",
"updated_at": "2021-05-17 20:41:53"
"url": the url from profiles table
}
]
我尝试制作一个 join 如下所示,但它返回带有所有 url 的两个元素。所以输出是带有两个网址的第一个数组,然后是带有两个网址的第二个元素:
public function profile($id)
{
$data = DB::table('socials')->where('profile_id','=', $id)
->join('profiles', 'url', '=', 'profiles.url')
->groupBy('profile_id')
->get();
return $data;
}
答案 0 :(得分:1)
Laravel'sk
方法是使用 Eloquent 模型来解决您的问题。
你的模型看起来像这样。
use Illuminate\Database\Eloquent\Model;
class Social extends Model
{
public function profile()
{
return $this->belongsTo(Profile::class);
}
}
class Profile extends Model
{
}
这里有两种解决方案,简单的方法是使用 with()
包含配置文件,
return Social::with('profile')->get();
将呈现以下结构。
{
"id": 4,
...
"profile": {
"url": the url from profiles table
}
},
这不是您想要的,您可以在 Laravel
中使用 getter。在您的社交模型上添加以下内容。为了使 getter 工作,它需要遵循 getColumnAttribute 函数命名。要将列添加到模型转换,请将其添加到 $appends
array
。
class Social extends Model
{
protected $appends = ['issues'];
public function getUrlAttribute()
{
return $this->profile->url;
}
}
这会产生预期的结果,您仍然需要包含 Profile 模型以进行性能优化。
return Social::with('profile')->get();
{
"id": 4,
"url": the url from profiles table
"profile": { ... }
},