Laravel 5.1从连接表中获取数据

时间:2016-04-17 17:00:11

标签: php laravel model laravel-5.1 belongs-to

在我的应用admin users中可以创建articles。文章表格是:ID | user_id | title ...

对于每个Article其他用户(非管理员)可以发布offer并且优惠表为:ID | user_id(not admin) | article_id | price ...

现在,我需要get all users管理员用户发布其文章的优惠...我尝试:

 public function userbase()
    {
        $id = Auth::user()->id;//get admin id
        $articles = Article::where('user_id', $id)->get();//select all admin articles
        foreach ($articles as $article) {

         $users = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get(); //get all admin users

        }


         return $users;


    }

但我得到:[]

我的模特也是: 的文章:

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

优惠

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

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

那么我如何才能将所有发布的用户详细信息提供给管理员用户?

更新

我也试试这个:

$articles = Article::with([
  'offers' => function($query) {
    $query->orderBy('created_at', 'desc');
    $query->with('user'); // if you want to eager load users for each offer too...
  }
])->where('user_id', Auth::id())->get();

我得到了这些数据:http://i.imgur.com/0kBVGrx.png

但如何访问user数据?我试试->get('user')但不行......

2。 UPDATE:

我也试试:

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

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

        }
    foreach ($offers as $offer) {

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

        }

        return $users;
}

但是我得到了未定义的变量用户

1 个答案:

答案 0 :(得分:1)

试试这个:
首先,您可以添加属性' isAdmin'在您的用户模型中。

public function userbase()
{
    return Offer::select('users.*')
                ->where('users.isAdmin', false)
                ->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()
 {
  $articles = Auth::user()->articles;
    foreach ($articles as $article) {

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

    }
    $users = array();
    foreach ($offers as $offer) {

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

    }

    return $users;
 }