Laravel保存子记录,但将外键设置为null

时间:2017-01-30 20:37:09

标签: mysql laravel-5 eloquent

这必须是一个简单的解决方案,因为我之前已经做了很多次。但就目前而言,我完全被难倒了。我使用以下代码来保存父对象Unknown_Tag及其许多子对象。

方法:

public function saveUnknown(Request $request)
{
    $url = $request->url;
    $tag = new Unknown_Tag();
    $tag->url = $url;
    $protocol =
        substr($url, 0, strpos($url, ':'));
    $tag->protocol = $protocol;
    $domain =
        parse_url($url, PHP_URL_HOST);
    $tag->domain = $domain;
    $tag->save();

    //get the path
    $Path = parse_url($url, PHP_URL_PATH);
    if ($Path) {
        $splitPath = substr($Path, 1);
        $paths = explode('/', $splitPath);
        foreach ($paths as $p) {
            $path = new Path();
            $path->path = $p;
            $tag->Paths()->save($path);
        }
    }
    //get Queries
    $splitQuery = parse_url($url, PHP_URL_QUERY);
    if ($splitQuery) {
        $queries = explode('&', $splitQuery);
        foreach ($queries as $q) {
            $query = new Query();
            $q = substr($q, 0, strpos($q, '='));
            IF (SUBSTR($q, -1) != ' ') {
                $q .= ' ';
            }
            $query->var = $q;
            $value = $q = preg_replace('/^[^=]*:/', '', $q);
            $query->value = $value;
            $tag->Queries()->save($query);
        }
    }
}

父对象

class Unknown_Tag extends Model
{
    protected $table = 'unknown_tags';
    public $timestamps = false;
    public function Paths()
    {
        return $this->hasMany('App\Path', 'tag_id', 'ID');
    }
    public function Queries()
    {
        return $this->hasMany('App\Query', 'tag_id', 'ID');
    }
}

儿童对象

class Query extends Model
{
    protected $table = 'queries';
    public $timestamps = false;
    public function Tag()
    {
        return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
    }
}

class Path extends Model
{
    protected $table = 'paths';
    public $timestamps = false;
    public function Tag()
    {
        return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
    }

}

当我通过post请求运行所有这些时,Parent和所有子节点都被正确保存,但是所有子对象都有一个设置为null的外键。如果我手动将外键更改为它应该是什么,一切正常,所以我很确定这不是我的数据库的问题。任何人都能看到我在这里失踪的显而易见的事情吗?

编辑:要清楚,这不会返回任何错误

1 个答案:

答案 0 :(得分:1)

如果有人见过这个,laravel会认为默认的主键是' id'。我已将我的设置为“ID'”,所以我必须通过使用

让laravel知道

protected $ primaryKey =' ID';

在我的Unknown_tag定义中