假設,有兩個表'student'和'state','student'表包含'id','name','state_id'。和'state'表包含'id','state_name'。在“學生”表中包含相應的州 ID。
現在我想獲取學生的詳細資訊,包括州名。(注意:在學生表中,我只包含狀態 id)我怎樣才能做到這一點?
uj5u.com熱心網友回復:
也許這可以幫助你:
學生.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Student extends Model
{
use HasFactory;
protected $fillable = ["id", "name", "state_id"];
public function state()
{
return $this->belongsTo(User::class, 'user_id');
}
}
學生控制器.php
public function show($id)
{
$student = Student::where('id', $id)->with('state')->get();
}
uj5u.com熱心網友回復:
嘗試這個
在您的學生模型中
public function state()
{
return $this->belongsTo(State::class, 'state_id');
}
現在您可以通過州獲取學生詳細資訊
public function show($id)
{
$student = Student::with('state')->find($id);
//for access the state name
//$student->state->state_name
}
uj5u.com熱心網友回復:
學生模式
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function state()
{
return $this->belongsTo( State::class );
}
}
讓學生有狀態
$students = Student::query()->with( 'state' )->get()
按州名搜索學生
$state = 'Dhaka';
$students = Student::query()->whereHas( 'state', function ( $query ) use ( $state ) {
$query->where( 'state_name', 'like', "%{$state}%" );
} )->paginate( 10 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/483617.html
