繁体   English   中英

来自Laravel关系模型的分页数据

[英]Paginate data from relationship model in Laravel

抱歉,如果标题不完全有意义...我不确定模型链接的确切术语是否是其控制器中的关联数据。

我正在尝试使用用户创建的帖子对表进行分页。

我设法对它进行了分页,而在posts表中没有user_id。 但是我已经将user_id添加到posts表中,并运行正常的迁移。

以下是我的Post模型:

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Post extends Model
    {
      public function user(){
        return $this->belongsTo('App\User');
      }
    }

这是我的User模型:

    namespace App;

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable
    {
        use Notifiable;
        protected $fillable = ['name', 'email', 'password',];

        protected $hidden = ['password', 'remember_token',];

        public function posts() {
          return $this->hasMany('App\Post');
        }
    }

这是后控制器的相关部分:

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Post;
    use App\User;
    use Session;
    use Carbon\Carbon;

    class PostController extends Controller
    {

      public function index()
      {

        $user_id = auth()->user()->id;
        $user = User::find($user_id);

        return view('posts.index')->with('posts', $user->posts);
      }

我认为这只是在PostController$user附加->paginate(5)一种情况,但这似乎不起作用。

我得到以下内容:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts

我尝试过将{!! $posts->links() !!} {!! $posts->links() !!}@foreach之前的posts.index视图中,但可以得到:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts

我正在尝试通过创建此Crud应用程序来学习Laravel基础知识,并尝试将两个教程结合在一起,但是我显然缺少了一些东西。

您可以在这样的关系上调用->paginate() (因为我已经删除了不必要的用户查询,因为auth()->user()已经执行了它):

public function index()
{
    $user = auth()->user();
    $posts = $user->posts()->paginate();
    // Or with 1 line: $posts = auth()->user()->posts()->paginate();
    return view('posts.index')->with('posts', $posts);
}

暂无
暂无

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

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