Laravel链表查询
文章描述:
Laravel使用模型链表查询数据
数据库
teacher 老师表
字段id、t_name、s_id
student 学生表
字段id、s_name
使用命令创建教师、学生模型文件
php artisan make:model User/Teacher
php artisan make:model User/Student
Teacher模型
namespace App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
use HasFactory;
protected $table = 'Teacher as a';
public $timestamps = false;
public function index(){
return $this->select('a.id','a.t_name','a.s_id','b.s_name')
->leftJoin('student AS b','a.s_id','=','b.id')
->get()->toArray();
}
}
Student模型
namespace App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'student';
public $timestamps = false;
}
控制器/方法
public function Test(){
$model = new Teacher();
$list = $model->index();
echo "<pre>";
// print_r($list);
$json = JSON_encode($list,JSON_UNESCAPED_UNICODE);
return $json;
}
发布时间:2023/03/21
发表评论