Many-to-one consultation laravel

0

I have a doubt in a controller with a relation of many (Product) to one (Brand), I try to search in Product to show the relationship 'Brand' but apparently I have an error because when using where() to search In Product and then show the relation the controller does it to me the other way around, he uses the where() in the related table giving me the error that the field 'link_id' does not exist in the table' brand 'but what I want is to find link_id in the product table.

$ejemplo = Producto::where('enlace_id', $id)->with('marca')->get();

Product Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Producto extends Model
{
    protected $fillable = [
        'enlace_id'
    ];

    public function marca()
      {
          return $this->belongsTo('App\Marca', 'id', 'enlace_id');
      }

}

Brand Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Marca extends Model
{

  protected $fillable = ['nombre'];


   public function producto()
  {
      return $this->hasMany('App\producto', 'enlace_id', 'id');
  }

}
    
asked by jorge 19.11.2018 в 13:04
source

1 answer

1

Your query that you do in a line, you could do it in two steps like this: Example:

$marcas = Marca::select('id')->get();
return Producto::whereIn('enlace_id', $marcas->toArray())->get();

Thus, you would look in the product table as you want.

Greetings.

    
answered by 19.11.2018 / 13:54
source