lundi 30 janvier 2017

Laravel saves child record, but sets foreign key to null

This has got to be a simple fix, as I have done this many times before. But as it stands I am completely stumped. I use the following code to save a parent object Unknown_Tag and its many children.

Method:

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);
        }
    }
}

The Parent Object

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');
    }
}

The Child objects

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');
    }

}

When I run all this via a post request, The Parent and all the children are saved properly, but all the child objects have a foreign key that is set to null. If I manually change the foreign key to what it should be, everything works just fine, so I am fairly sure this is not a problem with my database. Can anyone see the obvious that I am missing here?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2jODlFv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire