我在与状态的变形关系中有两个模型(类别和通道)(活动,非活动)。
在创建新类别或新频道时,我需要将活动状态分配给新创建的元素。为此,我需要传递$ type(频道或类别)和" statusable "的ID。元件。
这是我的CategoryController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\CategoriesRequest;
use App\Profile;
use App\Status;
use Session;
use Auth;
class CategoriesController extends Controller
{
public function store(CategoriesRequest $request)
{
$category = Category::create([
'title' => $request->title,
'slug' => str_slug($request->title, '-'),
'about' => $request->about,
]);
$category->save();
$type = 'categories';
$id = $category->id;
$status = (new Status)->create($id, $type); <-- Hier I am passing the two variables to the function CREATE in Status Model
Session::flash('success', 'Category successfully created!');
return redirect()->route('categories.show', $category->slug);
}
}
使用CREATE方法接收STATUS模型,接收两个变量
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Status;
Relation::morphMap([
'channels' => 'App\Channel',
'categories' => 'App\Category',
]);
class Status extends Model
{
protected $fillable = [
'status',
'statusable_type',
'statusable_id',
];
public function statusable()
{
return $this->morphTo();
}
public static function create($id, $type)
{ // I do hier dd($id); and dd($type) and the two variables have a value
$status = Status::create([
'statusable_id' => $id,
'statusable_type' => $type,
'status' => 'active', // I get the error here!
]);
$status->save();
return $status;
}
}
我确认这两个变量在方法的开头就到达 CREATE 方法(我看,如果我 dd()它)。但是在我收到此错误之后有两行:
类型错误:函数App \ Status :: create()的参数太少,第41行的C:\ laragon \ www \ streets \ app \ Status.php中传递的参数为1,预计正好为2
我做错了什么?
编辑:我有自己的解决方案: 如果有人感兴趣
我已将Controller中的调用更改为:
$type = 'categories';
$id = $category->id;
Status::create_status($id, $type);
然后在状态模型中:
public static function create_status($id, $type)
{
$status = new Status;
$status->statusable_id = $id;
$status->statusable_type = $type;
$status->status = 'active';
$status->save();
return $status;
}