Laravel查询 - 获取在admin用户文章

时间:2016-04-17 19:13:56

标签: php laravel model eloquent

因此,当我写标题时,我需要让所有向管理员用户发帖的用户... 所以我写道:

public function userbase()
{
    return Offer::select('users.*')
                ->where('users.admin', 9)
                ->join('articles','articles.id','=','offers.article_id')
                ->join('users','users.id','=','articles.user_id')
                ->where('articles.user_id', Auth::user()->id)
                ->orderBy('offers.created_at', 'desc')
                ->groupBy('users.id')
                ->get(); 
}

但我只是[](这不是真的)...

我也试试:

public function userbase()
{
     $user_ids = Article::where('user_id', Auth::id())
                ->join('offers')->on('offers.article_id', '=', 'articles.id')
                ->join('users')->on('offers.user_id', '=', 'users.id')
                ->select('users.id')
                ->distinct()
                ->get();

  $users = User::whereIn('id', $user_ids);
  return $users;
}

但我明白了: 缺少Illuminate \ Database \ Query \ Builder :: join()

的参数2
  1. 尝试是:

    public function userbase(){$ articles = Auth :: user() - > articles() - > get(); foreach($ article as $ article){

     $offers = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get();
    
    }
    

    foreach($ offer as $ offer){

     $users = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
    
    }
    
    return $users;
    

    } 但是外包不工作......

  2. 现在我真的不知道下一步该做什么......请帮助...

    也是我的模特: 文章:

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

    优惠:

    public function user() {
      return $this->belongsTo('App\User');
    }
    
    public function article() {
      return $this->belongsTo('App\Article');
    }
    

    那么我如何才能将发布优惠的用户提供给其他用户(管理员)文章......

2 个答案:

答案 0 :(得分:0)

尝试将此功能放在用户模型中:

public function scopeBase($query){
    $sql = <<<SQL
id IN(
    SELECT DISTINCT users.id FROM articles
    INNER JOIN offers
        ON articles.id=offers.article_id
    INNER JOIN users 
        ON users.id=articles.user_id
    WHERE articles.user_id=? AND users.admin=?
)   
SQL;

    return $query->whereRaw($sql, [$this->id, 9]);
}

然后在控制器中让用户使用以下语法:

class MyController extends Controller{
    public function example(){
        $users = User::base()->get();
        //....
    }

}

但是,如果你更好地解释表结构,你将不胜感激。

答案 1 :(得分:-1)

你试过这个吗?

foreach (User::all() as $user) {
foreach ($user->offers as $offer) {
        if ($offer->article->user->isAdmin()) 
            $select[] = $user;
   }
}