简体   繁体   English

使用laravel雄辩地检索所有记录

[英]retrieve all records with laravel eloquent

I tried following the docs here but didn't get the desired result, My tables looks like 我尝试按照此处的文档操作但未获得所需的结果,我的表​​看起来像

users table 用户表

id (pk - int) | username,

tweets table 鸣叫表

id (pk - int) | user_id (fk - int) | tweet(varchar)

User Model 用户模型

public function tweets() {
   return $this->hasMany('App\Tweet', 'user_id); // user_id is FK
}

Tweet Model 鸣叫模型

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

And on the controller side, I'am using eloquent to retrieve data. 在控制器方面,我正在雄辩地检索数据。 I have this method, 我有这种方法

public function ajax($id) {
    $data = User::with('tweets')->find($id)->tweets();
    return $data;
}

I tried following the logic here but I'm getting the following error on the controller code: 我尝试遵循此处的逻辑但在控制器代码上遇到以下错误:

Trying to get property of non-object 试图获取非对象的属性

Try using ->get(); 尝试使用->get(); to fetch all the records. 获取所有记录。

Why not simply do like: 为什么不简单地这样做:

$User = User::find($id);
$tweets = Tweet::whereUserId($id)->get(); // or ->paginate(20);
return compact('User', 'tweets');

ps I know about eager loading, but it does the same operation + it also does additional but unnecessary operation to join tweets collection to User object. ps我知道急切的加载,但是它执行相同的操作+它还会执行其他但不必要的操作,以将tweets集合连接到User对象。

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

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