加入Laravel 4.2中的表格Eloquent

时间:2015-04-08 11:02:38

标签: php mysql laravel-4 eloquent

我不太擅长使用Laravel Eloquent进行查询。我有两张桌子

stories table
------------------------------------------------------------------
 id |   title   |   body   | author_id |...
------------------------------------------------------------------
 1  | Story 1   | Once a.. |  2
 2  | Story 2   | There is |  4
 3  | Something | You are. |  2

 activities table
------------------------------------------------------------------
 id | story_id | liker_id |...
------------------------------------------------------------------
 1  | 2        | 2

此处author_id& liker_id实际上是user_id。我想通过特定的用户创作故事,以便在他的个人资料中显示这些故事。

我想使用Eloquent ORM。我使用查询构建器

尝试了类似的东西
 $stories = DB::table('stories')
                ->join('activities', function($join)
                {
                  $join->on('stories.author_id', '=', 'activities.liker_id')
                })
                ->where('stories.author_id', $author_id)
                ->get();
 return $stories;

我可以story_id获取特定liker_id的{​​{1}},但无法使用joinstories表格中获取详细信息strong>单个查询。

1 个答案:

答案 0 :(得分:1)

这是查询构建器的简单方法,可以让特定用户创建和喜欢Stories

$author_id = 1;
$stories = DB::table('stories')
            ->join('activities', 'stories.author_id', '=', DB::raw('activities.liker_id AND stories.id = activities.story_id'))
            ->Where('stories.author_id', $author_id)
            ->get();
//select * from `stories` inner join `activities` on `stories`.`author_id` = activities.liker_id AND stories.id = activities.story_id where `stories`.`author_id` = 1"
  

使用Eloquent,您可以执行以下创建2模型文件   1.故事模型(Story.php)   2.活动模型(Activity.php)   Story.php

class Story extends Eloquent {

    public function activities()
    {
        return $this->hasMany('Activity');
    }

}

Activity.php

class Activity extends Eloquent {

    public function story()
    {
        return $this->belongsTo('Story');
    }

}

比在Story中编写函数可以根据需要获取数据

$stories = Story::with('activities')
                    ->where(DB::raw('stories.id = activities.story_id'))
                    ->Where('stories.author_id', $author_id)
                    ->get();
// haven't tested with eloquent but it should work