[英]consult select in laravel with eloquent
我從Laravel開始,我有兩個簡單的實體,分別是用戶和注釋,它們之間的關系如下:
用戶
public function notes()
{
return $this->hasMany('App\Note');
}
筆記
public function user()
{
return $this->belongsTo('App\User');
}
現在,在我的控制器筆記中雄辯地說,我想返回我擁有的所有筆記,但是除了接收用戶的ID之外,我還想返回它的名稱,而我必須在的關系中指定一些內容這兩個實體,或者只是我應該在查詢中調整某些內容,目前我正在使用此方法:
$notes = Note::orderBy('id', 'desc')->get();
您可以按以下方式檢索用戶名:
$notes = Note:: orderBy ('id', 'desc') -> get ();
foreach ($notes as $note)
{
$name = $note->user->name;
}
如果要使用“ user_name”傳遞整個$ note數據,請首先定義您自己的類。 這樣的事情。
class my_class{
public $data;
public $user_name;
}
您可以在獲取$ note變量后立即運行循環,並將數據保存為此代碼的新數組。
$notes = Note::orderBy('id', 'desc')->get();
//define an empty Array
$data_arry=array();
foreach($notes as $note)
{
$custom=new my_class();
$name=User::where('u_user_id', $note->n_user_id)->limit(1)->get();
//First 'u_user_id' for column name in user table second 'n_user_id' for column name in note table
$user_name=$name[0]->u_user_name; // 'u_user_name' for column name of stored the name in user table
//pushing data to the object
$custom->data=$note;
$custom->user_name=$user_name;
$data_arry[]=$custom;
}
現在,您可以使用新的陣列管理數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.