简体   繁体   English

Laravel 通过关系获取数据

[英]Laravel get data in through relation

I use this hasOneThrough to get user through post to display result inf file :我使用这个hasOneThroughuser通过post显示结果 inf file

Controller控制器

File::where('agent_id', $user->id)
                ->with(['user' => function ($q) {
                    $q->select('name','phone');
                }])->get(['post_id', 'status']);

Model模型

// __________________________ related__|__through_|_1key_|_2key_|_lkey_|_seclkey

return $this->hasOneThrough('App\User', 'App\Post', 'id', 'id', 'post_id', 'user_id');

// ___________________________________________^ > want to get `hash` from `post`

This work good, but now I need one item from post called hash in this result, is it possible to get any data from through (Post table).这个工作很好,但现在我需要一个来自post项目,在这个结果中称为hash ,是否有可能through (帖子表)中获取任何数据。 Already able to get any data from file and user but how can I get data from through (Post table) ?已经能够从fileuser中获取任何数据,但是如何through (Post 表)获取数据?

I don't know how can do this, so I searched and nothing found, so I couldn't try anything.我不知道该怎么做,所以我进行了搜索但没有找到任何东西,所以我无法尝试任何事情。

If your File table has a post_id , and between posts and files table there is a One to Many relation, just declare a new relation:如果您的File表有一个post_id ,并且在postsfiles表之间存在一对多关系,只需声明一个新关系:

public function post(){
   return $this->belongsTo('App\Post', 'post_id', 'id');
}

Also keep in mind that if inside a with you want to select only specific fields, you can just do ->with('user:phone,name')还要记住,如果在with你只想选择特定的字段,你可以做->with('user:phone,name')

You should use hasOne in your model:您应该在模型中使用hasOne

public function post(){
    return $this->hasOne('App\Post', 'id', 'post_id');
}

And in your controller you can use eager loading but I noticed you get null , in order for this to work, you also have to select the id:在你的控制器中你可以使用预先加载,但我注意到你得到了null ,为了让它工作,你还必须选择 id:

$files = File::where('agent_id', $user->id)->with('user:phone,name', 'post:id,hash')->get(['post_id', 'status']);

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

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