2016-08-28 52 views
2

我的架构如下:我如何在laravel中使用关系?

channel table: 
id int unsigned primary key auto increment, 
name varchar(30) not null, 
... 

category table: 
id int unsigned primary key auto increment, 
channel_id int unsigned index, 
name varchar(30) not null, 
... 

article table: 
id int unsigned primary key auto increment, 
category_id int unsigned index, 
title varchar(90) not null, 
content text not null, 
... 

所以,每一篇文章都属于一个特定的类别和类别属于特定的通道。

我的问题是:

我如何可以搜索所有与类别名称和频道名称的文章(的关系是在我的代码准备好)?

我曾尝试

$articles = App\Article::latest()->with('category')->with('channel')->get(); 

,但它不工作,谁可以帮我?感谢您的时间。

回答

0

如果你想通过你应该使用相关的表搜索加入这样的:

$articles = App\Article::latest() 
    ->select('article.*') 
    ->join('category', 'category.id', '=', 'category_id') 
    ->join('channel', 'channel.id', '=', 'channel_id') 
    ->where('category.name', 'LIKE', "%{$name}%") 
    ->orWhere('channel.name', 'LIKE', "%{$name}%") 
    ->groupBy('article.id') 
    ->get(); 
+0

谢谢你的建议〜 – Snriud

相关问题