現在下記のようなUserモデルを作成しました。
リレーションでUserのFavoriteを吐き出したいです。
一旦Controllerで吐き出したく、その場合のコードはどのようにすべきでしょうか。
Controller、Tableも参考までにご参考ください。
php
1<?php 2//User.php(Model) 3 4namespace App; 5 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use App\Favorite; 8 9class User extends Authenticatable 10{ 11 /** 12 * The attributes that are mass assignable. 13 * 14 * @var array 15 */ 16 protected $fillable = [ 17 'name', 'email', 'password', 18 ]; 19 20 /** 21 * The attributes that should be hidden for arrays. 22 * 23 * @var array 24 */ 25 protected $hidden = [ 26 'password', 'remember_token', 27 ]; 28 29 30 public function favorites() 31 { 32 return $this->hasMany(Favorite::class, 'id', 'user_id'); 33 } 34} 35
mysql> select*from favorites; +----+---------+----------+---------------------+---------------------+ | id | user_id | favorite | created_at | updated_at | +----+---------+----------+---------------------+---------------------+ | 1 | 14 | 12 | 2016-09-08 03:31:41 | 2016-09-08 02:32:46 | | 2 | 12 | 38 | 2016-09-16 02:13:49 | 2016-09-16 00:13:47 | | 3 | 14 | 17 | 2016-09-16 04:13:51 | 2016-09-16 00:13:51 | | 4 | 14 | 21 | 2016-09-16 04:14:43 | 2016-09-16 00:14:59 | | 5 | 14 | 46 | 2016-09-16 04:14:44 | 2016-09-16 00:14:00 | | 6 | 11 | 63 | 2016-09-16 23:20:06 | 2016-09-16 21:20:36 | | 7 | 11 | 46 | 2016-09-16 23:20:50 | 2016-09-16 23:20:50 | +----+---------+----------+---------------------+---------------------+
php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Http\Requests; 7use DB; 8use App\Http\Controllers\Controller; 9use App\Favorite; 10use App\User; 11 12 13class TestController extends Controller 14{ 15 16 public function favoritepage( $id ) 17 { 18 $user = User::all(); 19 $favorites = $user->favorites()->where('id', $id)->get(); 20 21 echo $favorites; 22 23 24 }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/20 04:06
2016/09/20 04:08
2016/09/20 13:05
2016/09/20 15:25
2016/09/20 16:23