我有一個領域: post
id userId
2beaa4b5-4c53-4652-b2c3-34ecfe627acd 9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf
4dfaa4b5-3r45-4652-b2c3-34ecfewsa345 f45aa3b5-4c53-4f52-b2c3-49ecfe543bde
后模型:
<?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;
}
在控制器中,我通過 userId 獲取用戶:
$user = Post::where('userId', '9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf')->get();
userId除了where之外,還有其他方法可以獲取其他資訊嗎?例如找到?請給我你的意見。謝謝。
uj5u.com熱心網友回復:
find()只是where()在主鍵欄位上添加子句并執行查詢的簡寫。也就是說,Post::find($id)== Post::where('id', $id)->first()。
呼叫get()將始終回傳 a Collection,即使沒有結果。我假設您的查詢僅回傳一條記錄。如果是這種情況,您將需要使用first()而不是get(),因為這將回傳找到的記錄,或者null如果沒有記錄則回傳。
$user = Post::where('userId', '9beaa3b5-4c53-4f52-b2c3-49ecfe627ebf')->first();
uj5u.com熱心網友回復:
您可以使用 Laravel 關系。在您的 Post 模型上添加:
public function user()
{
return $this->belongsTo(User::class, 'userId');
}
在您的 User 模型中,您可以添加:
public function posts()
{
return $this->hasMany(Post::class, 'userId');
}
現在,如果您使用該$user變數,您可以像這樣獲取該用戶的所有帖子:
$posts = $user->posts()->get();
反之亦然,如果你有一個$post,你可以像這樣獲得 $user:
$user = $post->user;
更多資訊在這里:
https://laravel.com/docs/8.x/eloquent-relationships
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344424.html
標籤:拉拉维尔
