繁体   English   中英

我如何在Laravel中使用关系?

[英]how can i use relationship in 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();

但这不起作用,有人可以帮助我吗? 感谢您的时间。

如果要搜索相关表,则应使用如下联接:

$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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM