前提・実現したいこと
テキストの投稿システムを作っています。
投稿内容の表示はできました。
ユーザーテーブルと紐付けして投稿者名を表示したいです。
発生している問題
Userテーブルの内容を紐付けができない
該当のソースコード
User.php
PHP
1<?php 2 3namespace App; 4 5use Illuminate\Notifications\Notifiable; 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use Illuminate\Database\Eloquent\Model; 8 9class User extends Authenticatable 10{ 11 use Notifiable; 12 13 /** 14 * The attributes that are mass assignable. 15 * 16 * @var array 17 */ 18 protected $fillable = [ 19 'name', 'email', 'password', 20 ]; 21 22 /** 23 * The attributes that should be hidden for arrays. 24 * 25 * @var array 26 */ 27 protected $hidden = [ 28 'password', 'remember_token', 29 ]; 30 31 public function posts() 32 { 33 return $this->hasMany(Post::class); 34 } 35} 36
Post.php
PHP
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Post extends Model 8{ 9 protected $fillable = [ 10 'user_id', 11 'emoji', 12 ]; 13 14 public function users() 15 { 16 return $this->belongsTo(User::class); 17 } 18}
PostsController.php
PHP
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Post; 7 8class PostsController extends Controller 9{ 10 public function index() 11 { 12 //$posts = Post::orderBy('created_at', 'desc')->get(); 13 $posts = Post::orderBy('created_at', 'desc')->paginate(10); 14 15 // userテーブルの内容を取得できているか確認 16 $p = Post::find(1); 17 var_dump($p->users); // nullになる 18 19 return view('posts.index', ['posts' => $posts]); 20 } 21(以下省略)
試したこと
UserモデルとPostモデルに、hasManyとbelongToを設定
補足情報(FW/ツールのバージョンなど)
PHP 7.1
Laravel 5.5
テーブルの情報(2019/08/24 21:20追記)
mysql> desc posts; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | user_id | int(10) unsigned | NO | MUL | NULL | | | emoji | text | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)
mysql> desc users; +----------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | email | varchar(255) | NO | UNI | NULL | | | password | varchar(255) | NO | | NULL | | | remember_token | varchar(100) | YES | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +----------------+------------------+------+-----+---------+----------------+ 7 rows in set (0.00 sec)
データ(2019/08/24 21:50追記)
mysql> select * from posts where id = 1; +----+---------+---------------+---------------------+---------------------+ | id | user_id | emoji | created_at | updated_at | +----+---------+---------------+---------------------+---------------------+ | 1 | 1 | りんご???? | 2019-08-14 11:38:05 | 2019-08-14 11:38:05 | +----+---------+---------------+---------------------+---------------------+ 1 row in set (0.00 sec) mysql> select * from users where id = 1; +----+-------+-------------------+--------------------------------------------------------------+--------------------------------------------------------------+---------------------+---------------------+ | id | name | email | password | remember_token | created_at | updated_at | +----+-------+-------------------+--------------------------------------------------------------+--------------------------------------------------------------+---------------------+---------------------+ | 1 | user1 | user1@example.com | $2y$10$oFI7Koi/jEx/ghZhjce4HOEFzQGHcGpTT5xERyNNM9CqF0DY8jOXq | WVygmE7sHrYhSSYQ7fHOQH6kctJJrau0mHSHf2ZhMSqdsz3YvWNF55rJyu85 | 2019-08-14 11:11:54 | 2019-08-14 11:11:54 | +----+-------+-------------------+--------------------------------------------------------------+--------------------------------------------------------------+---------------------+---------------------+ 1 row in set (0.00 sec)
$p = Post::find(1);
この時点で $p は値撮れてますか?
$pが取れていない場合、null のプロパティusersにアクセスしようとしたとしてエラーになるはずです
回答ありがとうございます。
Post::find(1); は値取れていました。
array (size=5)
'id' => int 1
'user_id' => int 1
'emoji' => string 'りんご????' (length=13)
'created_at' => string '2019-08-14 11:38:05' (length=19)
'updated_at' => string '2019-08-14 11:38:05' (length=19)
プログラムソース自体におかしなところは見受けられません。
単純に該当するデータがないだけのように見えます。
barryvdh/laravel-debugbar などデバッグツールを入れて、発行されているSQLを確認してみては?
ありがとうございます。
デバッグツール初めて知りました。
試してみます!
$p->users()
をダンプしたらなんか出ますか?
↓がでました
app/Http/Controllers/PostsController.php:17:
object(Illuminate\Database\Eloquent\Relations\BelongsTo)[206]
protected 'child' =>
object(App\Post)[217]
protected 'fillable' =>
array (size=2)
0 => string 'user_id' (length=7)
1 => string 'emoji' (length=5)
protected 'connection' => string 'mysql' (length=5)
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'keyType' => string 'int' (length=3)
public 'incrementing' => boolean true
protected 'with' =>
array (size=0)
empty
protected 'withCount' =>
array (size=0)
empty
protected 'perPage' => int 15
public 'exists' => boolean true
public 'wasRecentlyCreated' => boolean false
protected 'attributes' =>
array (size=5)
'id' => int 1
'user_id' => int 1
'emoji' => string 'りんご????' (length=13)
'created_at' => string '2019-08-14 11:38:05' (length=19)
'updated_at' => string '2019-08-14 11:38:05' (length=19)
protected 'original' =>
array (size=5)
'id' => int 1
'user_id' => int 1
'emoji' => string 'りんご????' (length=13)
'created_at' => string '2019-08-14 11:38:05' (length=19)
'updated_at' => string '2019-08-14 11:38:05' (length=19)
protected 'changes' =>
array (size=0)
empty
protected 'casts' =>
array (size=0)
empty
protected 'dates' =>
array (size=0)
empty
protected 'dateFormat' => null
protected 'appends' =>
array (size=0)
empty
protected 'dispatchesEvents' =>
array (size=0)
empty
protected 'observables' =>
array (size=0)
empty
protected 'relations' =>
array (size=1)
'users' => null
protected 'touches' =>
array (size=0)
empty
public 'timestamps' => boolean true
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'guarded' =>
array (size=1)
0 => string '*' (length=1)
protected 'foreignKey' => string 'users_id' (length=8)
protected 'ownerKey' => string 'id' (length=2)
protected 'relation' => string 'users' (length=5)
protected 'query' =>
object(Illuminate\Database\Eloquent\Builder)[201]
protected 'query' =>
object(Illuminate\Database\Query\Builder)[207]
public 'connection' =>
object(Illuminate\Database\MySqlConnection)[197]
...
public 'grammar' =>
object(Illuminate\Database\Query\Grammars\MySqlGrammar)[203]
...
public 'processor' =>
object(Illuminate\Database\Query\Processors\MySqlProcessor)[204]
...
public 'bindings' =>
array (size=6)
...
public 'aggregate' => null
public 'columns' => null
public 'distinct' => boolean false
public 'from' => string 'users' (length=5)
public 'joins' => null
public 'wheres' =>
array (size=1)
...
public 'groups' => null
public 'havings' => null
public 'orders' => null
public 'limit' => null
public 'offset' => null
public 'unions' => null
public 'unionLimit' => null
public 'unionOffset' => null
public 'unionOrders' => null
public 'lock' => null
public 'operators' =>
array (size=29)
...
public 'useWritePdo' => boolean false
protected 'model' =>
object(App\User)[216]
protected 'fillable' =>
array (size=3)
...
protected 'hidden' =>
array (size=2)
...
protected 'connection' => string 'mysql' (length=5)
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'keyType' => string 'int' (length=3)
public 'incrementing' => boolean true
protected 'with' =>
array (size=0)
...
protected 'withCount' =>
array (size=0)
...
protected 'perPage' => int 15
public 'exists' => boolean false
public 'wasRecentlyCreated' => boolean false
protected 'attributes' =>
array (size=0)
...
protected 'original' =>
array (size=0)
...
protected 'changes' =>
array (size=0)
...
protected 'casts' =>
array (size=0)
...
protected 'dates' =>
array (size=0)
...
protected 'dateFormat' => null
protected 'appends' =>
array (size=0)
...
protected 'dispatchesEvents' =>
array (size=0)
...
protected 'observables' =>
array (size=0)
...
protected 'relations' =>
array (size=0)
...
protected 'touches' =>
array (size=0)
...
public 'timestamps' => boolean true
protected 'visible' =>
array (size=0)
...
protected 'guarded' =>
array (size=1)
...
protected 'rememberTokenName' => string 'remember_token' (length=14)
protected 'eagerLoad' =>
array (size=0)
empty
protected 'localMacros' =>
array (size=0)
empty
protected 'onDelete' => null
protected 'passthru' =>
array (size=12)
0 => string 'insert' (length=6)
1 => string 'insertGetId' (length=11)
2 => string 'getBindings' (length=11)
3 => string 'toSql' (length=5)
4 => string 'exists' (length=6)
5 => string 'doesntExist' (length=11)
6 => string 'count' (length=5)
7 => string 'min' (length=3)
8 => string 'max' (length=3)
9 => string 'avg' (length=3)
10 => string 'sum' (length=3)
11 => string 'getConnection' (length=13)
protected 'scopes' =>
array (size=0)
empty
protected 'removedScopes' =>
array (size=0)
empty
protected 'parent' =>
object(App\Post)[217]
protected 'fillable' =>
array (size=2)
0 => string 'user_id' (length=7)
1 => string 'emoji' (length=5)
protected 'connection' => string 'mysql' (length=5)
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'keyType' => string 'int' (length=3)
public 'incrementing' => boolean true
protected 'with' =>
array (size=0)
empty
protected 'withCount' =>
array (size=0)
empty
protected 'perPage' => int 15
public 'exists' => boolean true
public 'wasRecentlyCreated' => boolean false
protected 'attributes' =>
array (size=5)
'id' => int 1
'user_id' => int 1
'emoji' => string 'りんご????' (length=13)
'created_at' => string '2019-08-14 11:38:05' (length=19)
'updated_at' => string '2019-08-14 11:38:05' (length=19)
protected 'original' =>
array (size=5)
'id' => int 1
'user_id' => int 1
'emoji' => string 'りんご????' (length=13)
'created_at' => string '2019-08-14 11:38:05' (length=19)
'updated_at' => string '2019-08-14 11:38:05' (length=19)
省略
何かしら出てくればリレーションの設定は正しそうですね(Typoとかなし)
あなたの回答
tips
プレビュー