我有这3张桌子,一个帖子可以被多个用户查看:
用户
帖子
user_posts
我如何使用Eloquent仅向用户显示他有权访问的帖子?
谢谢
答案 0 :(得分:0)
我认为您已经正确设置了模型,在用户模型上是这样的:
public function posts(){
return $this->belongsToMany("App\Post");
}
要仅获取单个用户创建的帖子,请在您的控制器中尝试此操作(使用急切加载来限制数据库查询):
$user = \App\User::with('posts')->find($someInputUserId_orAuthUserId);
$posts = $user->posts;
答案 1 :(得分:0)
假设
代码是
//users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class users extends Model
{
public function posts()
{
return $this->hasMany("App\posts");
}
public function userPosts()
{
return $this->hasMany("App\userpost");
}
}
帖子模型
//posts.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class posts extends Model
{
public function user()
{
return $this->belongsTo("App\users");
}
}
用户发布模型(此处是用户和发布它们已被访问)
//userpost.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class userpost extends Model
{
public function users(){
return $this->hasMany("App\users");
}
public function posts()
{
return $this->hasMany("App\posts","id","post_id");
}
}
控制器可以写为
//PostViewController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\posts;
use App\users;
use App\userpost;
class PostViewController extends Controller
{
public function view()
{
$user_id = 2; //user_id of the user you want to view
$posts= userpost::where('user_id', $user_id)->get();
//return $posts; you can return $posts and view it on "view" by using foreach as shown below
foreach($users as $user)
{
return $user->posts;//posts is the function made in model.
}
}
}
此处,foreach循环仅执行一次,因此只有一个帖子,因为return结束了循环。只是为了说明如何获取帖子数据,可以根据获取数据来完成