2017-09-01 64 views
0

有三个表在我的系统:如何通过Laravel口才得到的只是一个表

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

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

文章型号

class Articles extends Model 
{ 
    protected $fillable = ['id','title', 'body', 'students_id', 'created_at', 'updated_at']; 
    protected $table = 'articles'; 

    public function students(){ 
     return $this->belongsTo('App\Students'); 
    } 

    public function categories(){ 
     return $this->belongsTo('App\Categories'); 
    } 
} 

我创建了上面的代码,因为我需要去与谁通过文章与类别名称写的文章列表。

为此,我在控制器中使用了$article_list = Articles::get();,并且它完美地工作。

然后我又需要获得文章列表(这次我不需要学生名称和类别名称;文章表格的输出绰绰有余)。

但是,如果我使用$article_list = Articles::get();它也输出与类别和学生表连接的文章表。

有没有办法只用文章表雄辩

+0

您可以使用此查询生成器 –

+0

*您输出的文章表格与类别和学生*相连是什么意思?是否确定学生和类别数据实际上* id *在你得到的结果中,还是这些只是在雄辩模型上的关系对象? – lesssugar

+0

@lesssugar是的。在使用'$ articles = Articles :: with('students') - > with('categories') - > get();'和'$ articles = Articles :: get();'时,我会得到相同的结果。因为这个,我感到困惑。我的意思是在foaeach之后,我可以使用'{{$ article ['categories'] ['name']}}'来访问类别名称。所以我知道他们已经加入了...... –

回答

1

Eloquent内的关系是急切的加载,所以你是安全的,并且类别也被加载无害。从该文档引用:

当访问作为属性口才关系,该关系 数据是“延迟加载”。这意味着关系数据不是 实际加载,直到您第一次访问该属性。

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

+0

这是正确的答案。 –

+0

@ Don'tPanic性能如何? –

+0

@IamtheMostStupidPerson你的表现很好。数据实际上并没有加载,只要您首先访问属性。这是急切加载的好处。 – jjj

0

尝试:

class Articles extends Model 
{ 
    protected $fillable = ['id','title', 'body', 'students_id', 'created_at', 'updated_at']; 
    protected $table = 'articles'; 

    public function students(){ 
     return $this->belongsTo('App\Students'); 
    } 

    public function categories(){ 
     return $this->hasOne('App\Categories'); 
    } 
} 

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

你可以尝试有许多通过关系

官方链接:read more

0

@ JJJ的答案是正确的,但在bi中解释t更多细节:

$articles = Articles::get(); 

将加载唯一的文章。你可以在你的控制器检查它是这样的:

public function articles() { 
    $articles = Articles::get(); 
    return $articles; 
} 

$articles是模型的集合,每一种模式是它的关系,“知道”。因此,如果您尝试访问其中一种关系,Laravel会默默为您加载。所以,如果你通过上面相同$articles到您的视图(目前无类别),然后在你看来做这样的事情:

@foreach ($articles as $article) 
    {{ $article->categories->name }} 
@endforeach 

它会工作,因为Laravel是做SQL找到每篇文章的类别,然后名称。正如@jjj解释的那样,这称为延迟加载,并在文档中进行了描述。

顺便说一下,像这样的延迟加载通常效率低下,并且它会更好地加载,就像您在上面的注释中显示的那样。 It is described well in the docs