如何根据多对多相关模型的字段值访问模型的记录

How to access records of a model based on a field value of many to many related model

我正在使用 laravel 5.3。有2个型号。

Job [id,title,location]

Tag [id,tag_name].

两个模型有关系many to many

Job belongstomany Tag

Tag belongstomany Job.

支点table是,

job_tag [job_id,tag_id].

如何获取与特定标签名称关联的工作记录。

标签:

id.     |     tag_name
--------|--------------------------
1       |          php
--------|--------------------------
2       |          html
--------|--------------------------

职位:

id       |    title               |     location
---------|------------------------|--------------------------
1        |   developer            |      Kochi
---------|------------------------|--------------------------
2        |   designer             |      bangalore
---------|------------------------|--------------------------

枢轴:job_tag:

job_id           |     tag_id
---------------- |-----------------
    1            |       1
-----------------|-----------------
    1            |       2
-----------------|-----------------
    2            |       1
-----------------|-----------------

使用标签名称 "php",我想列出与标签名称 "php" 相关的所有作业。

https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

这可能对您有所帮助。

//$params[tags] contains the data for the search

$jobs = Job::query();
$jobs = Job::whereHas('tags', function ($query) use($params) {
    $query->whereIn('tag_name', $params['tags']);
});

上面的代码对我有用... https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence