【问题标题】:Laravel eloquent pagination call in relational database关系数据库中的 Laravel 雄辩分页调用
【发布时间】:2019-09-04 00:21:14
【问题描述】:

我有一个用户。用户创建了许多广告。我想通过分页显示的广告查看用户详细信息。为此,我制作了两个模型(用户和广告)

public function user(){

     return $this->hasOne(User::class, 'id', 'user_id');
}

public function ads(){

    return $this->hasMany(Ads::class, 'user_id', 'id');
}

在控制器中我这样调用:

$users = Ads::with(['user'=> function ($q) use ($id){
        $q->where('id',$id);
    }])->paginate(2);

但是当调用 forelse 循环时,这里会显示用户的详细信息。但我不想要这个。 那么,如何通过广告的分页获取用户的详细信息?

【问题讨论】:

  • 如果它是相同的关系,为什么你要传递 2 个不同的外键给关系?
  • 抱歉错误,已编辑。

标签: php laravel eloquent-relationship


【解决方案1】:

我认为你过于复杂了。 你有两个模型。 在用户中,你可以把这个关系:

public function ads(){
    return $this->hasMany(App\Ad, 'user_id', 'id');
}

在 Ads 模型中,您提出了这种关系:

public function user(){
     return $this->belongsTo(App\User, 'id', 'user_id');
}

在您的控制器中,您可以像这样简单地调用:

//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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2015-03-14
    • 2018-11-28
    • 2015-01-11
    • 2021-06-03
    • 2020-03-26
    相关资源
    最近更新 更多