【发布时间】:2020-09-25 10:00:59
【问题描述】:
这是我的模型:
// 专业模型
class Specialties extends Model
{
protected $guarded = [];
protected $table = 'specialties';
protected $primaryKey = 'id';
protected $fillable = [
'name', 'region_id', 'description', 'picture', 'url', 'author', 'code'
];
public function regions()
{
return $this->belongsTo('App\Regions', 'id');
}
}
// 区域模型
class Regions extends Model
{
protected $table = 'regions';
protected $primaryKey = 'id';
public function specialties()
{
return $this->hasMany('App\Specialties', 'region_id');
}
}
// 我的控制器功能添加新的专业
public function store(Request $request, Recaptcha $recaptcha)
{
$validatedData = $request->validate([
'name' => 'required|string|max:50',
'region' => 'required|integer',
'description' => 'required|string|max:1000',
'image_file' => 'required|file|mimes:jpeg,jpg,png,gif|max:2048',
'url' => 'nullable|string|max:2000',
'author' => 'nullable|string|max:50',
'recaptcha' => ['required', $recaptcha],
]);
Storage::disk('public')->putFileAs('/img/uploads/specialties', new File($validatedData['image_file']), pathinfo($validatedData['image_file']->getClientOriginalName(), PATHINFO_FILENAME) . time() . '.' . $validatedData['image_file']->getClientOriginalExtension());
$code = str_slug($validatedData['name'], "-");
$image_name = pathinfo($validatedData['image_file']->getClientOriginalName(), PATHINFO_FILENAME) . time() . '.' . $validatedData['image_file']->getClientOriginalExtension();
$specialty = Specialties::create([
'name' => $validatedData['name'],
'region_id' => $validatedData['region'],
'description' => $validatedData['description'],
'picture' => $image_name,
'url' => $validatedData['url'],
'author' => $validatedData['author'],
'code' => $code
]);
return response(['specialty' => $specialty], 201);
}
// 我的函数有问题:
public function index()
{
$actives = Specialties::with('regions')
->where('active', 1)
->get();
$inactives = Specialties::with('regions')
->where('active', 0)
->get();
return [
'actives' => $actives,
'inactives' => $inactives
];
}
我的问题是 with('regions') 在最后一个函数中返回 null,例如,如果我创建一个新的专业“StackOverflow”:
active: 1
author: null
code: "stackoverflow"
created_at: "2020-09-24T16:59:29.000000Z"
description: "blablabla"
id: 18
name: "StackOverflow"
picture: "test600966769.jpg"
region_id: 1
regions: null <- Here the problem
updated_at: "2020-09-24T16:59:50.000000Z"
url: null
有人知道这个问题吗?谢谢!!!
【问题讨论】:
标签: php laravel eloquent relationship