首页 > 解决方案 > Laravel, use middleware to find Domain, then get Website row using Domain row.

问题描述

I want to use some middleware to get a row from a website table, this row is referenced within my domains table.

This is my middleware so far:

<?php

    namespace App\Http\Middleware;

    use App\Domains;
    use Closure;

    class Domain
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {

            $domainRow = Domains::where([ 'domain' => $_SERVER['HTTP_HOST'] ])->first();

            dd($domainRow->website);

            return $next($request);
        }
    }

And here is my Domains model, which works fine except the hasOne part:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Domains extends Model
    {

        public function website()
        {
            return $this->hasOne('App\Website');
        }

    }

The hasOne part is generating the below query:

Unknown column 'websites.domains_id' in 'where clause' (SQL: select * from websites where websites.domains_id = 2 and websites.domains_id is not null limit 1)

However the query I need it to make is:

SELECT * FROM websites WHERE id = 1

Where 1 is from the website_id column within the Domains table.

标签: phplaravel

解决方案


将网站方法更改为:

public function website() 
{
    return $this->belongsTo('App\Website');
}

推荐阅读