I have a field : post
id userId
2beaa4b5-4c53-4652-b2c3-34ecfe627acd 9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf
4dfaa4b5-3r45-4652-b2c3-34ecfewsa345 f45aa3b5-4c53-4f52-b2c3-49ecfe543bde
post model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $table = 'post';
protected $keyType = 'string';
public $incrementing = false;
protected $connection = 'product';
public $timestamps = false;
}
In controller, I get user by userId :
$user = Post::where('userId', '9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf')->get();
Is there any other way to get the userId
other than where? eg find? Please give me your opinion. Thanks.
CodePudding user response:
find()
is just a shorthand for adding a where()
clause on the primary key field and executing the query. That is, Post::find($id)
== Post::where('id', $id)->first()
.
Calling get()
will always return a Collection
, even if there are no results. I'm assuming that your query is meant to only return one record. If that is the case, you'll want to use first()
instead of get()
, as that will either return the one found record, or it will return null
if there are no records.
$user = Post::where('userId', '9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf')->first();
CodePudding user response:
You can use Laravel Relationships. On your Post model add:
public function user()
{
return $this->belongsTo(User::class, 'userId');
}
And in your User model you can add:
public function posts()
{
return $this->hasMany(Post::class, 'userId');
}
Now if you're using the $user
variable, you can get all the posts of that user like this:
$posts = $user->posts()->get();
And vice versa, if you have a $post
, you can get the $user like this:
$user = $post->user;
More info here: