The
has() method can be used to check whether something is related. Generally, other has methods are used to determine whether there is a value in it
<span style="color: #800080;">$packageOrders</span> = Company::has('packages'<span style="color: #000000;">)->get();<br>dd(</span><span style="color: #800080;">$packageOrders</span>);
The meaning of the has method in this sentence is different. What is its detailed logic, how to relate it, and how to query it. First, let’s take a look at what dd($packageOrders) outputs
You can see that the output is also the element of company, and the total data obtained is 18. If you use
<span style="color: #800080;">$packageOrders</span> = Company::all();<span style="color: #000000;"> dd(</span><span style="color: #800080;">$packageOrders</span>);
all() method is used to get it. You can see that the printed data is more than 100. So what is the has method used to filter, resulting in only 18 result data?
$packageOrders = Company::has('packages'<span>)->get();<br>这句话的详细意思就是,先去company找和packages关联的那张表,看他们互相匹配的id是哪些数据,大概意思是这,首先去company模型查找与之对应的</span>
packages方法
那么packages方法是与app\CompanyPackage模型关联的,他们关联的ID是company_id,第三个参数表示用自己的ID值 去和companyPackage里的company_id匹配<br>那么到数据库的流程就是 先去company表里查找id的值,在到company_packages表中查看company_id的值,有没有匹配的,取出所有匹配的数据,匹配的数据取出的是company表的,不会带出
company_packages表的数据,也就是文章开头显示的数据了。<br><br>那么如果现在company模型里面的packages方法,第二个参数改为package_id的话,查询情况又会如何呢
那么 $packageOrders = Company::has('packages')->get(); 会到数据库里查company表里的id 和 company_packages表package_id互相匹配的值 在显示出来,<br>筛选就是这么筛选的,所以all()方法100多条数据,而has只有18条互相匹配的数据了
<br><br>
<br><br>