【问题标题】:Laravel eloquent multiple table join with filterLaravel 雄辩的多表连接与过滤器
【发布时间】:2018-02-10 09:49:42
【问题描述】:

我的系统中有表格。

  1. 学生
  2. 文章
  3. 类别

一个学生可以写很多篇文章,一篇文章只属于一个学生。而且一篇文章只能有一个类别。

控制器

public function all_articles_by_student_by_category(Request $request){


        $students_id = $request->students_id;
        $categories_id = $request->categories_id;


        $article_list = Students::find($students_id)->articles->all();

        //This return Something like, Select All Articles Written by Damith
    }

型号

class Students extends Model
{
    protected $fillable = ['id','first_name', 'last_name', 'age', 'created_at', 'updated_at'];

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

我想得到什么

类似,为技术类别选择 Damith 撰写的所有文章(类别名称应该在那里)

到目前为止我能做到的事情

类似,使用 $article_list = Students::find($students_id)->articles->all(); 选择 Damith 撰写的所有文章(您可以从控制器中找到此代码)

我想从你这里得到什么

如何修改$article_list = Students::find($students_id)->articles->all(); 以获取类似“选择所有由 Damith 撰写的文章作为技术类别”之类的信息。 (类别名称必须在结果中,并且在类别表中,并且在条件下您可以使用文章表中的 category_id

【问题讨论】:

  • 答案很简单,请查看 Laravel 文档了解如何使用 eloquent。如果你能够做一个简单的 SQL 查询,这意味着你可以用 eloquent 来做。只需学习语法。

标签: php laravel laravel-5 laravel-eloquent laravel-5.5


【解决方案1】:

首先你到目前为止所做的事情在获取模型关系的记录时不需要->all() 方法,这将返回链接到该学生的所有文章:

Students::find($students_id)->articles

浏览文章模型
你可以这样做:

Article::where('student_id', $students_id)
  ->where('category_id', $category_id)->get();

这会达到你想要的结果。


通过学生模型

如果你想通过StudentsModel你可以使用with方法约束关系。

$student = Students::with(['articles' => function($query) use ($category_id) {
  $query->where('category_id', $category_id);
}])->find($student_id);

$filteredArticles = $student->articles

有用的链接

当访问 Eloquent 关系作为属性时,关系数据是“延迟加载”的。这意味着在您第一次访问该属性之前,不会实际加载关系数据。但是,Eloquent 可以在查询父模型时“预先加载”关系。

有时您可能希望预先加载关系,但还要为预先加载查询指定额外的查询约束。

【讨论】:

  • 感谢您的详细回答。我正在阅读这篇文章,Article::where('student_id', $students_id) ->where('category_id', $category_id)->get(); 工作正常。 .我以为这个返回只是select * from articles where student_id=2 and categories_id=3.......现在我的问题是Laravel如何知道文章表和类别表应该加入where('category_id', '=', $categories_id)行?
  • @IamtheMostStupidPerson 如果您还有其他问题,请点击 按钮提出问题。你需要充分解释你现在想要什么帮助。请参阅 Laravel 文档:laravel.com/docs/5.5/eloquent-relationships
  • @IamtheMostStupidPerson 如果您还想保留学生的数据,您可能想尝试Go through Students Model 方法。
【解决方案2】:

这样的事情应该可以工作:

$technologyArticles = Articles::where('student_id', '=', $students_id)->where('category_id', '=', $categories_id)->get();

【讨论】:

  • 谢谢。这行得通。我以为这个返回只是select * from articles where student_id=2 and categories_id=3.......现在我的问题是Laravel如何知道文章表和类别表应该加入where('category_id', '=', $categories_id)行?
  • @IamtheMostStupidPerson 如果您还有其他问题,请点击 按钮提出问题。您需要充分说明您现在想要什么帮助。请参阅 Laravel 文档:laravel.com/docs/5.5/eloquent-relationships
猜你喜欢
  • 1970-01-01
  • 2020-03-24
  • 2014-07-01
  • 2018-06-03
  • 1970-01-01
  • 2020-11-16
  • 2020-04-26
  • 1970-01-01
  • 2016-10-05
相关资源
最近更新 更多