Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RoughLik's avatar

Get data with 3 relationships

Hi, I have a relationship on 3 tables, how could I make a query to take the data according to the id I have + the 3 relationships?

$id = Auth::user()->company_id;

        $data = Popup::getPopupByCompanyId($id);
        $biases = Bias::getBiasByCompanyId($id);
        $discounts = DiscountCode::getDiscountsByCompany($id);
        $introductionMessages = IntroductionMessage::getDiscountsByCompany($id);

I take them like that now, but how could I make a whereHas all 3? this is relationsship from biases, discount, introduction to Popup model

 $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('discount_code_id')->references('id')->on('discount_codes')->onDelete('cascade');

And I can only take all that data with company_id, how could I do a whereHas function in which company_id is the main thing I am guided by and join it after company id data May?

0 likes
3 replies
anilkumarthakur60's avatar

if you have set up your model relationship correctly then

$variable=Model_name::with('model_relationship1')->with('model_relationship2')->with('model_relationship3')->get();
RoughLik's avatar
Call to a member function addEagerConstraints() on null in file

Models
Bias
 public function discount_codes()
    {
        $this->hasMany(DiscountCode::class);
    }
DiscountCode
	 public function biases() 
    {
        $this->belongsTo(Bias::class);
    }

Migration
Bias
 $table->integer('discount_code_id')->nullable()->unsigned();
$table->foreign('discount_code_id')->references('id')->on('discount_codes')->onDelete('cascade');

Discount Code
$table->increments('id');
            $table->string('discount_code')->nullable();

Please or to participate in this conversation.