teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

UserモデルとBlogモデルの追加

2021/03/02 02:20

投稿

tkm-mkzk
tkm-mkzk

スコア4

title CHANGED
File without changes
body CHANGED
@@ -110,6 +110,96 @@
110
110
  @endsection
111
111
  ```
112
112
 
113
+ ```php
114
+ <?php
115
+
116
+ //Models/User.php
117
+
118
+ namespace App\Models;
119
+
120
+ use Illuminate\Contracts\Auth\MustVerifyEmail;
121
+ use Illuminate\Database\Eloquent\Factories\HasFactory;
122
+ use Illuminate\Foundation\Auth\User as Authenticatable;
123
+ use Illuminate\Notifications\Notifiable;
124
+
125
+ class User extends Authenticatable
126
+ {
127
+ use HasFactory, Notifiable;
128
+
129
+ /**
130
+ * The attributes that are mass assignable.
131
+ *
132
+ * @var array
133
+ */
134
+ protected $fillable = [
135
+ 'name',
136
+ 'email',
137
+ 'password',
138
+ ];
139
+
140
+ /**
141
+ * The attributes that should be hidden for arrays.
142
+ *
143
+ * @var array
144
+ */
145
+ protected $hidden = [
146
+ 'password',
147
+ 'remember_token',
148
+ ];
149
+
150
+ /**
151
+ * The attributes that should be cast to native types.
152
+ *
153
+ * @var array
154
+ */
155
+ protected $casts = [
156
+ 'email_verified_at' => 'datetime',
157
+ ];
158
+
159
+ public function blogs(){
160
+ return $this->hasMany('App\Models\Blog');
161
+ }
162
+
163
+ public function weights(){
164
+ return $this->hasMany('App\Models\Weight');
165
+ }
166
+
167
+ public function selectUserFindById($id)
168
+ {
169
+ $query = $this->select([
170
+ 'id',
171
+ 'name',
172
+ 'email'
173
+ ])->where([
174
+ 'id' => $id
175
+ ]);
176
+ // first()は1件のみ取得する関数
177
+ return $query->first();
178
+ }
179
+ }
180
+ ```
181
+
182
+ ```php
183
+ <?php
184
+
185
+ //Models/Blog.php
186
+
187
+ namespace App\Models;
188
+
189
+ use Illuminate\Database\Eloquent\Factories\HasFactory;
190
+ use Illuminate\Database\Eloquent\Model;
191
+
192
+ class Blog extends Model
193
+ {
194
+ use HasFactory;
195
+
196
+ public function user(){
197
+ return $this->belongsTo('App\Models\User');
198
+ }
199
+
200
+ }
201
+ ```
202
+
113
203
  ### 補足情報(FW/ツールのバージョンなど)
114
204
 
115
205
  userモデルとblogモデルはリレーションを組んであります。

1

いらないコメントの削除

2021/03/02 02:20

投稿

tkm-mkzk
tkm-mkzk

スコア4

title CHANGED
File without changes
body CHANGED
@@ -20,7 +20,6 @@
20
20
 
21
21
  // 検索フォーム
22
22
  $query = DB::table('blogs');
23
- // ->join('blogs', 'blog.id', '=', 'blogs.user_id')
24
23
 
25
24
  // もしキーワードがあったら
26
25
  if($search !== null){