laravel:多表查询之一对多(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/eloquent-relationships/14889
二,php代码:
1,model中定义方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class SUser extends Model{ use HasFactory; //定义关联的数据表 protected $table = 'user'; //定义主键 protected $primaryKey = 'user_id'; // 时间字段是否自动管理(created_at 和 updated_at字段) public $timestamps = false; //读取一条数据 public function getOneById($userId) { //$all = $this->get(); return $this->where('user_id', $userId)->first(); } //添加数据 public function add($row) { $int = $this->insert($row); return $int; } //得到用户所转的新闻列表 public function news() { //hasMany第一个参数:关联表的model类 //第二个参数:关联表的关系字段(news表) //第三个参数: 本表的关系字段(user表) return $this->hasMany(News::class,'user_id','user_id'); } |
2,controller 中调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class NewsController extends Controller{ public function user(Request $request) { //默认连接,启用sql log DB::enableQueryLog(); $model = new SUser(); $obj = $model->getOneById(1); $data = $obj->news; $logNews = DB::getQueryLog(); //返回 return ['data'=>$data, 'log'=>$logNews, ]; } |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/24/laravel-duo-biao-cha-xun-zhi-yi-dui-duo-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,测试效果:

四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0

浙公网安备 33010602011771号