G
G
GaserV2016-10-02 11:33:54
Laravel
GaserV, 2016-10-02 11:33:54

Why is the connection not working?

Good afternoon. For the third day I still can’t understand why the records are not getting? I'll go crazy soon.
On business. There are tables users, orders, items. Orders: id,user_id,item_id;
User model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model 
{	

  public $timestamps = false;

  protected $table = 'users';

  protected $fillable = ['','firstname','lastname','login','password','email','phone','adress','signup-date','total-orders','activated','type'];

  public function orders()
  {
    return $this->belongsToMany('App\Order');
  }

}

I'm trying to output as @foreach($user->orders as $order) but I get an error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fivegsm.id' doesn't exist (SQL: select `orders`. *, `id`.`user_id` as `pivot_user_id`, `id`.`order_id` as `pivot_order_id` from `orders` inner join `id` on `orders`.`id` = `id`.`order_id` where `id`.`user_id` = 4) (View: /Applications/MAMP/htdocs/blog/resources/views/user/orders.blade.php)
What am I doing wrong?(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2016-10-02
@Alex_Wells

There you go again with your "$this->belongsTo". I already explained to you that "belongsTo" - "THIS belongs to someone/something" .. so your "User" (THIS = $this) belongs to "App\Order"? No, of course, the user has many orders, that is, "$this->hasMany('App\Order')" - literally translated "THIS has many orders", and "THIS" = $this = User.
And now Order belongs to User, that is, the Order belongs to the user, and in the order model you already use belongs to User.
I hope it's clear)
PS: don't use protected $table, it's useless.
PS: https://vk.com/five_gsm_boss - do you make a website for them?)) 0 Do not name the database by the name of the project.

D
Dmitry Evgrafovich, 2016-10-02
@Tantacula

belongsToMany doesn't apply at all in this situation - it's a many-to-many relationship. You can use it to get the Items of specific users, and even then, if you write the Orders table as an intermediate one. Use hasMany to get orders and read carefully the difference between all kinds of relationships in the documentation. Very thoughtful. Because until you realize the differences in the types of communication, you will not be able to use them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question