Php Laravel:连接并返回所有元素
My社交表格的控制器输出以下内容:Php Laravel:连接并返回所有元素,php,mysql,laravel,Php,Mysql,Laravel,My社交表格的控制器输出以下内容: [ { "id": 4, "value": "FaAlgolia", "name": "zaefzaef", "profile_id": 4, "order": 9000,
[
{
"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
}
]
我试着创建一个连接,如下所示,但它返回两个元素和所有url。因此,输出是带有两个URL的第一个数组,然后是带有两个URL的第二个元素:
public function profile($id)
{
$data = DB::table('socials')->where('profile_id','=', $id)
->join('profiles', 'url', '=', 'profiles.url')
->groupBy('profile_id')
->get();
return $data;
}
Laravel'sk
的方法是使用雄辩的模型来解决你的问题
你的模特看起来就是这样
use Illuminate\Database\Eloquent\Model;
class Social extends Model
{
public function profile()
{
return $this->belongsTo(Profile::class);
}
}
class Profile extends Model
{
}
这里有两种解决方案,简单的方法是使用with()
包含概要文件
将介绍以下结构
{
"id": 4,
...
"profile": {
"url": the url from profiles table
}
},
这并不是您想要的,相反,您可以在Laravel
中使用getter。在您的社交模型中添加以下内容。为了让getter工作,它需要遵循getColumnAttribute函数命名。要将列添加到模型转换中,请将其添加到$appends
数组中
class Social extends Model
{
protected $appends = ['issues'];
public function getUrlAttribute()
{
return $this->profile->url;
}
}
这将产生预期的结果,您仍然需要包含用于性能优化的概要文件模型
return Social::with('profile')->get();
{
"id": 4,
"url": the url from profiles table
"profile": { ... }
},
非常感谢您的回复。我已经有了这个模型,但没有想过要这样使用它<代码>社交::with(profiles)
的工作原理与您提到的完全相同,但在执行第二个代码时,我出现了一个错误意外的“$appends”
。我很好奇是否有可能通过添加一个->select
?谢谢。我用附录更新了我的答案,这是可能的,但使用雄辩的模型更为夸张,如果你想的话,我明天可以写一个例子:)我试过protected$appends=['url']相反,它工作得非常好。非常感谢你。虽然“profile”:{…}
将始终显示正确?我从未遇到过必须隐藏关系的情况,但对于列,您可以执行受保护的$hidden=['profile'];那么,也许可以试试看,它是否适用于人际关系?我明白了。我只是想知道就这样,它是否存在并不困扰我。
return Social::with('profile')->get();
{
"id": 4,
"url": the url from profiles table
"profile": { ... }
},