A
A
Alexander Shvedov2019-06-25 12:29:04
Laravel
Alexander Shvedov, 2019-06-25 12:29:04

Laravel one-to-many relationship how to access?

class department extends Model
{
    public function User()
    {
        return $this->hasMany('App\User','departments_id','id');
    }
}

class UserAll extends Model
{
    protected $table = 'users';
    protected $guarded = [];

    public function department()
    {
        return $this->belongsTo('App\Department','departments_id','id');
    }

}

public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('names');
            $table->string('description');
            $table->string('logo');
            $table->bigInteger('departments_id')->unsigned()->index();
            $table->foreign('departments_id')
                ->references('id')->on('users');
            $table->timestamps();
        });
    }

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

class DepartmertController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $comments = \App\Department::all();
        $departmens=$comments->User();
        dd($departmens);
        return view('department.index',compact('departmen','user'));
    }

how can I get the username that belongs to the link using the department I have already tried a lot of things everywhere errors the connection goes by the key foreign I want to pull out the object of the communication department to pull out the username that is associated with this department, the dock did not help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2019-06-25
@constintmid

in Department

public function users() {
  return $this->belongsToMany('App\User', 'user_department', 'departament_id', 'user_id');
}

in controller
$departaments = Department::with('users')
                          ->get();

in template
@foreach ($departaments as $departament)
  @foreach ($departament->users as $user)
    {{$user->name}}
  @endforeach
@endforeach

ManyToMany

A
Andrey Suha, 2019-06-25
@andreysuha

You should listen to what you are told. And about the question $ comments is a collection and not a model instance, this is an error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question