Php 关系数据库中的Laravel雄辩分页调用
我有一个用户。用户创建许多广告。我想看到用户的详细信息与广告,其中的广告显示分页。为此,我制作了两个模型(用户和广告) 在控制器中,我这样称呼:Php 关系数据库中的Laravel雄辩分页调用,php,laravel,eloquent-relationship,Php,Laravel,Eloquent Relationship,我有一个用户。用户创建许多广告。我想看到用户的详细信息与广告,其中的广告显示分页。为此,我制作了两个模型(用户和广告) 在控制器中,我这样称呼: $users = Ads::with(['user'=> function ($q) use ($id){ $q->where('id',$id); }])->paginate(2); //If you want a list of User's Ads $user = User::find(1); $use
$users = Ads::with(['user'=> function ($q) use ($id){
$q->where('id',$id);
}])->paginate(2);
//If you want a list of User's Ads
$user = User::find(1);
$userAds = $user->ads()->paginate(2); //you paginate because can be many
//If you want the details from a user who made the Ad #1
$ad = Ad::find(1);
$user = $ad->user; //Don't need paginate because is only one.
但在这里,调用forelse循环时会显示用户的详细信息。但我不想要这个。
那么,如何通过广告的分页来获取用户的详细信息呢?我认为你太复杂了。 你有两个模型。 在“用户”中,可以将此关系设置为:
public function ads(){
return $this->hasMany(App\Ad, 'user_id', 'id');
}
public function user(){
return $this->belongsTo(App\User, 'id', 'user_id');
}
在Ads模型中,您将此关系置于:
public function ads(){
return $this->hasMany(App\Ad, 'user_id', 'id');
}
public function user(){
return $this->belongsTo(App\User, 'id', 'user_id');
}
在控制器中,您可以这样简单地调用:
$users = Ads::with(['user'=> function ($q) use ($id){
$q->where('id',$id);
}])->paginate(2);
//If you want a list of User's Ads
$user = User::find(1);
$userAds = $user->ads()->paginate(2); //you paginate because can be many
//If you want the details from a user who made the Ad #1
$ad = Ad::find(1);
$user = $ad->user; //Don't need paginate because is only one.
如果是相同的关系,为什么要将两个不同的外键传递给关系?很抱歉,已编辑。