[英]retrieve data from table based on a foreignKey Laravel
So I have 2 tables, articles and sub_categories. 所以我有2个表,文章和sub_categories。 They are linked throug Eloquent: articles has many sub_categories's, and sub_categories belongsTo article.
它们通过Eloquent链接:文章有很多sub_categories,sub_categories属于文章。 They are linked with foreign keys as such: in "article" categorie_id.
它们与外键相关联:在“article”categorie_id中。
How do I retrieve the entire table data article where categorie is "DOG" for exemple Sorry for the abstraction, but this is the best way I can explain it? 如何检索整个表格数据文章,其中类别为“DOG”,例如对于抽象,这是我能解释的最佳方法吗? :D
:d
article model 文章模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Articles extends Model
{
use SoftDeletes;
public function user() {
return $this->belongsTo('App\User') ;
}
public function sous_categories() {
return $this->belongsTo('App\SouCategories') ;
}
}
sub_categorie model sub_categorie模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SouCategories extends Model
{
public function categories() {
return $this->belongsTo('App\Categories') ;
}
public function articles() {
return $this->hasMany('App\Articles','cat_id') ;
}
}
in my controller i am trying to fetch data based on the foreign key on the sub_category and foreach sub category i am creating an a array like the mainslider contain articles that have a certain sub_category 在我的控制器中我试图基于sub_category和foreach子类别上的外键获取数据我正在创建一个像mainslider这样的数组包含具有某个sub_category的文章
public function index()
{
$infos = Infos::all();
$categories = Categories::all();
$articles=Articles::all();
$mainslider=Soucategories::with('articles')->get();
foreach($mainslider as $record){
dd($record->articles);
}
die();
return view('frontEnd.homepage',compact('infos','categories','articles','mainslider'));
}
According to the code you have posted it should be something like 根据您发布的代码,它应该是类似的
Soucategories::where('title', 'DOG')->with('articles')->get();
it seems there will be only on Soucategory with name "DOG", so you can do something like 它似乎只有Soucategory上有名字“DOG”,所以你可以做类似的事情
Soucategories::where('title', 'DOG')->first()->articles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.