Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在拉雷维尔有许多人违约_Php_Laravel - Fatal编程技术网

Php 在拉雷维尔有许多人违约

Php 在拉雷维尔有许多人违约,php,laravel,Php,Laravel,在Laravel中-如果关系不返回任何值,是否有方法返回不同的集合 例如 课程主题 { 公共职能问题 { 返回$this->hasMany(问题::类); } } 这将返回主题的问题。但我需要的行为是,如果我查询$topic->questions(),它会返回一个 返回问题::get()->whereNull('topic_id')) 有人知道我怎样才能做到这一点吗 迁移: Schema::create('topics',函数(Blueprint$table){ $table->increm

在Laravel中-如果关系不返回任何值,是否有方法返回不同的集合

例如

课程主题
{
公共职能问题
{
返回$this->hasMany(问题::类);
}
}
这将返回主题的问题。但我需要的行为是,如果我查询
$topic->questions()
,它会返回一个

返回问题::get()->whereNull('topic_id'))
有人知道我怎样才能做到这一点吗

迁移:

Schema::create('topics',函数(Blueprint$table){
$table->increments('id');
$table->string('topic')->index();
$table->timestamps();
});
Schema::create('questions',函数(Blueprint$表){
$table->id();
$table->unsignedBigInteger('topic\u id')
->nulluble()
->注释(“链接到主题表”);
$table->foreign('topic\u id','fk\u topic\u question')
->引用('id')
->关于(‘主题’)
->onDelete(“级联”);
$table->string('question')->nullable();
$table->timestamps();
});
然后是默认问题种子示例:

$data=[
[
“问题”=>“默认问题1”
],
[
“问题”=>“默认问题2”
]
];
问题:插入($数据);

您可以使用
可选的
辅助功能:

为默认问题创建一个主题,并将已解决的问题与此主题关联,然后您可以使用此主题:

$questions = optional($preferTopic,$defaultTopic)->questions;

我决定了一个临时解决方案(有点老套,但做了我需要的):


然后,我使用
$topic->getQuestions()
而不是
$topic->questions()

来共享您的迁移以及您到目前为止所做的测试。因此,您想向查询添加一个只返回null
topic\u id
的条件吗?有点违背了关系的目的这会起作用,但不能满足我的需要。我对DB有限制,因为它不是仅由Laravel API使用的。
public function getQuestions()
    {
        if($this->questions()->get()->count()==0){
            return Question::all();
        }else{
            return $this->questions()->get();
        }

    }