我正在尝试将客户端和设备外键保存在我的查询表中但不知何故它一直保持返回null(我的迁移可以为空)。如果我返回$ Client或$ device,我会收到错误。返回正确的id。
控制器的外观如下:
# foreign key in this table rreturns null InquiryController
public function store(Request $request)
{
$input = $request->all();
$client = Client::find($request->input('client_id'));
$device = Device::find($request->input('device_id'));
$stream = new Stream;
$stream->stream_name = $request->input('stream_name');
$stream->save();
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);
$inquiry->save();
}
这是我的查询模式
class Inquiry extends Model
{
protected $table = 'inquiries';
protected $fillable = ['user_id', 'client_id', 'device_id', 'stream_id'];
# relations
public function user()
{
return $this->belongsTo(User::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
public function device()
{
return $this->belongsTo(Device::class);
}
public function stream()
{
return $this->belongsTo(Stream::class);
}
}
这是客户端和设备模型的关系函数:
public function inquiry()
{
return $this->hasMany(Inquiry::class);
}
迁移:
public function up()
{
Schema::create('inquiries', function(Blueprint $table)
{
$table->increments('id');
$table->unsignedInteger('client_id')->nullable();
$table->unsignedInteger('device_id')->nullable();
$table->timestamps();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('inquiries');
}
答案 0 :(得分:-1)
确保在inquiry
表的迁移中定义了外键。
例如:
$table->integer('client_id')->unsigned();
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
<强>更新强>
尝试在添加关系之前保存模型。将其交换为:
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->save();
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);