如何在InnoDB引擎上使用laravel 5.6删除行?

时间:2018-04-28 19:31:16

标签: php laravel innodb

我正在构建一个简单的项目管理Web应用程序,我将InnoDB作为我的表引擎,显然我无法删除"公司"至少拥有项目所以我试图使用适当的错误信息显示处理这种情况。

我的目标是告诉用户如果公司有项目并且我已经成功完成了该项目,那么该公司将被删除,除非我已删除该特定项目的所有项目公司从数据库中我仍然得到相同的信息"公司有项目..."

 */
public function destroy(Company $company)
{
    $current = Company::find($company->id);        

    if($current !== null){
        $companiesProjects = $current->projects;

        if($companiesProjects === null){
            if($current->delete()){
                return redirect()->route('companies.index')
                ->with('success', 'Company has been successfully deleted!');
            }
        }else{
            return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
        }
    }else{
        return back()->withInput()->with('errors', 'Company does not exist!');

    }

   return back()->withInput()->with('errors', 'Company could not be deleted!');
}
}

我尝试了另一个解决方案,即在将它的名称空间添加到资源控制器之后使用函数内部的Project对象但不幸的是我的php服务器停止运行而我的PC停止响应而我没有其他选择,但重新启动PC

 public function destroy(Company $company, Project $project)
     {
        $current = Company::find($company->id);

    if($current !== null){
        $companiesProjects = Project::where('company_id', $company->id);

        if($companiesProjects === null){
           /* if($current->delete()){
                //return redirect()->route('companies.index')
                //->with('success', 'Company has been successfully deleted!');
            }*/
            echo 'null';
        }else{
            //return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
        }
    }else{
        //return back()->withInput()->with('errors', 'Company does not exist!');

    }

   //return back()->withInput()->with('errors', 'Company could not be deleted!');
}

我只关注视频课程,而且我在文档中迷失了。

1 个答案:

答案 0 :(得分:1)

$company->projects将返回一个数组。填充的或空的。但无论哪种方式$company->projects === null都会返回false。

你应该这样做:

if(!$current->projects->count()) {
    // Empty
} else {
    // Not empty
}

我是否也对你有一些更清洁的逻辑感兴趣?

if ($company->projects->isNotEmpty()) {
    return back()->withInput()->with('errors', 'Company has projects... it can\'t be deleted!');
}
if (!$company->delete()) {
    return back()->withInput()->with('errors', 'Company could not be deleted!');
}
return redirect()->route('companies.index')
            ->with('success', 'Company has been successfully deleted!');

$current = Company::find($company->id)是不需要的。由于您正在使用模型绑定,$company将是alreaady实例,或者路由将返回404,这也消除了对第一个if块的需要。