Giter Club home page Giter Club logo

belongs-to-through's People

Contributors

andreshg112 avatar axlon avatar dannyweeks avatar dennislindsey avatar muhammedkamel avatar staudenmeir avatar wnateg avatar znck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

belongs-to-through's Issues

How can I change the name of the keys?

I need to do something like this:

public function sede() {
        return $this->belongsToThrough(Sede::class, Vendedor::class, [], 'vendedor_id');
    }

But when I do it, I got this:

QueryException in Connection.php line 729: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pedidos.vendedor_idvendedore_id' in 'on clause' (SQL: select sedes.*, pedidos.idas__deep_related_through_keyfromsedesleft joinvendedoresonsedes.id=vendedores.sede_idleft joinpedidosonvendedores.id=pedidos.vendedor_idvendedore_idwherepedidos.idin (2997, 2998) andsedes.deleted_at is null)

When I do it without the key and array:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pedidos.vendedore_id' in 'on clause' (SQL: select sedes.*, pedidos.idas__deep_related_through_keyfromsedesleft joinvendedoresonsedes.id=vendedores.sede_idleft joinpedidosonvendedores.id=pedidos.vendedore_idwherepedidos.idin (2997, 2998) andsedes.deleted_at is null)

I have a problem with it because you're using Str::singular. This is just for english words. How can I change the name of my foreign key?
Note: The plural for 'vendedor' is 'vendedores', in spanish.

BelongsTo > HasOne Relationship

Hi just wanted to ask if there's a way to connect belongsTo > HasOne relationship using the BelongsToThrought Trait.

I have a Admission Request > BelongsTo > Course > HasOne > PaymentTypes

Thank you for your answer! :)

through table is not joined as I want.

product
- idx_product  PK

sale_product
- idx_sale_product PK
- idx_sale

sale
- idx_sale PK

I've tried a lot and following logic is the closest.

// App\Models\Product

public function sale() {
  return $this->belongsToThrough('App\Models\Sale', 'App\Models\SaleProduct', null, '', [
     'App\Models\SaleProduct' => 'idx_sale_product',
     'App\Models\Sale' => 'idx_sale',
  ]);
}

However, the result of the query execution is not what I wanted.

select `sale`.* from `bp_sale` 
left join `sale_product` on `sale`.`idx_sale` = `sale_product`.`idx_sale` 
left join `product` on `sale_product`.`idx_sale` = `product`.`idx_sale_product` 

How can i change sale_product.idx_sale to sale_product.idx_sale_product ? (third line)
It's too harsh for me

Looking for maintainers

I have been away from PHP and Laravel for a while. It difficult for me to pay attention to this project. If you're interested in maintaining, please reach out.

hasMany to belongsTo

Hi

How would you go about this scenario:
Business → has many → AttachedServices → belongs to → service

Trying to use both of your packages, but struggling.

Thanks!

Use with whereHas

I could be cool if you could use the belongsToThrough in methods such as whereHas, has, etc.

Currently I have tested with whereHas and it fails with the error:

BadMethodCallException thrown with message "Call to undefined method Illuminate\Database\Query\Builder::getHasCompareKey()"

Stacktrace:
#128 BadMethodCallException in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2251
#127 Illuminate\Database\Query\Builder:__call in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1340
#126 call_user_func_array in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1340
#125 Illuminate\Database\Eloquent\Builder:__call in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:344
#124 call_user_func_array in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:344
#123 Illuminate\Database\Eloquent\Relations\Relation:__call in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:165
#122 Illuminate\Database\Eloquent\Relations\Relation:getRelationQuery in /home/vagrant/Projects/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:776
#121 Illuminate\Database\Eloquent\Builder:has in /home/vagrant/Projects/myapp/app/UserSubscription.php:43

Incorrect relation when the model is new and is not saved

Hello,

Didn't had the chance to look into a fix as of yet, maybe you know how to fix it more quickly heh

Here's the model i have

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Znck\Eloquent\Traits\BelongsToThrough;
use Illuminate\Database\Eloquent\SoftDeletes;

class CustomerEquipment extends Model
{
    use BelongsToThrough, SoftDeletes;

    public $table = 'customer_equipments';

    protected $fillable = [
        'customer_id',
        'serial_number',
        'manufacturer_model_id',
    ];

    public function manufacturer()
    {
        return $this->belongsToThrough(Manufacturer::class, ManufacturerModel::class);
    }
}

Note: Just removed some methods and docblocks that were not required.

If i do the following:

$equipment = new CustomerEquipment;

var_dump($equipment->manufacturer);

It returns a manufacturer object, which is wrong, it should return null since it's a fresh, not saved, model.

Entity hasOne IntermediateEntity belongsTo TargetEntity

School hasOne Address
Address belongsTo City

I want to define a relationship on School model that gives me the city it is located in.
The problem is, I have a hasOne instead of belongsTo relationship with the intermediate model.

class School extends Model
{
    public function address()
    {
        return $this->hasOne('App\Address');
    }

    public function city()
    {
        // What to do
    }
}

hasManyThrough - depth?

The belongsToThrough() can set up a relationship to an arbitrary depth. That is really great and useful.

The core eloquent hasManyThrough() only works to a depth of one, which is not so useful when you have a deep relationship to pull out of the database. Would you consider adding a hasManyThroughDeep() method to supplement what eloquent supports?

BelongToThrough does not respect Model's connection

BelongToThrough does not respect Model's connection

Database structure

Let's assume a database structure with three models in two different database schemas.

DB: dev_user_db

sellers
- id
DB: dev_shop_db

categories
- id
- seller_id

items
- id
- category_id

Database config

And the following config/database.php which let's us switch between a development and produciton database using the .env file:

return [
    'user_db' => [
        // Some other things here
        'database' => env('USER_DATABASE')
    ],
    'shop_db' => [
        // Some other things here
        'database' => env('SHOP_DATABASE')
    ],
];

Relationships

The relationships are defined as follows:

class Seller extends Model
{
    protected $connection = 'user_db';
    protected $table = 'sellers';

    // Some hasMany here ...
}

class Category extends Model
{
    protected $connection = 'shop_db';
    protected $table = 'categories';

    public function seller()
    {
        return $this->belongsTo(Seller::class);
    }
}

class Item extends Model
{
    protected $connection = 'shop_db';
    protected $table = 'items';

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function seller()
    {
        return $this->belongsToThrough(Seller::class, Category::class);
    }
}

Issue

When trying to retrieve an Item with it's Seller:

public function getItems()
{
    return Item::with(['seller'])->get();
}

The following SQL Exception is thrown:

"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dev_user_db.categories' doesn't exist 
(SQL: select `seller`.*, `categories`.`id` as `laravel_through_key` from `seller` inner join `categories` on `categories`.`seller_id` = `seller`.`id` where `categories`.`id` in (1, 2))"

As we can see, the query tries to find dev_user_db.categories even though $connection = 'shop_db' was defined on the Category model.

A possible suggested solution to this was to also define the schema's name in the table parameter like $table = 'dev_shop_db.categories. Unfortunately this is not possible here, since the schema's name changes depending on the .env file - and expressions are not allowed as field default values.

So it would be great if the belongsToThrough relationship used the defined $connection attributes to determine the correct database schemas to query.

whereHas is not working

MODEL

class Project extends Model
{
    public function categories()
    {
        return $this->hasMany('App\Category');
    }

    public function properties()
    {
        return $this->hasManyThrough('App\Property', 'App\Category');
    }
}
class Category extends Model
{
    public function project()
    {
        return $this->belongsTo('App\Project');
    }

    public function properties()
    {
        return $this->hasMany('App\Property');
    }
}
class Property extends Model
{
    use SoftDeletes, BelongsToThrough;

    public function project()
    {
        return $this->belongsToThrough('App\Project', 'App\Category');
    }

    public function category()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }
}

CONTROLLER

public function index(Request $request)
    {
        $page           = $request->input('page') ? $request->input('page') : 1;
        $itemsPerPage   = $request->input('itemsPerPage') ? $request->input('itemsPerPage') : 25;
        $search         = $request->input('search');
        $project_id     = $request->input('project_id');

        $properties      = Property::select('*')
            ->when($search, function ($query, $search) {
                return $query->where('name', "like", "%$search%");
            })
            ->with('project')
            ->when($project_id, function ($query, $project_id) {
                return $query->whereHas('project', function ($query) use ($project_id) {
                    return $query->where('id', $project_id);
                });
            })
            ->paginate($itemsPerPage);

        return $properties;
    }

ERROR

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select count(*) as aggregate from propertieswhere exists (select * fromprojectsinner joincategoriesoncategories.project_id=projects.idwherecategories.id=properties.category_idandid= 1 andcategories.deleted_atis null andcategories.deleted_atis null andprojects.deleted_atis null) andproperties.deleted_at is null)

PROBLEM

When we try to use whereHas relationship WHEN $project_id exist;

->when($project_id, function ($query, $project_id) {
                return $query->whereHas('project', function ($query) use ($project_id) {
                    return $query->where('id', $project_id);
                });
            })

if remove this whereHas eloquent builder, everything working fine include ->with('project')

Thanks

belongsTo > belongsTomany

Hi,

I don't know if I'm just making things complicated but I can't make this work.

I have a Course, Student and Teachers.

Student belongsTo > Course > belongsToMany > Teachers

And from student model I wanted to get directly the teachers

public function teachers()
    {
        return $this->belongsToThrough(Teacher::class, [Course::class, 'teacher_has_courses']);
    }

Thanks in advance.

Get one column with BelongsToThrough

Hi,

I have these tables :

shows :

  • id
  • name

seasons :

  • id
  • name
  • show_id

episodes :

  • id
  • name
  • season_id

My model Episode is like this :

/**
     * @return \Znck\Eloquent\Relations\BelongsToThrough
     */
    public function show()
    {
        return $this->belongsToThrough(Show::class, Season::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function season()
    {
        return $this->belongsTo('App\Models\Season');
    }

This works fine, but when I want to get only one column with belongs to through, it's doesn't work.
I have tried this :

$this->episode
     ->whereId($episode_id)
     ->with(['season:seasons.id', 'show' => function ($q) {
         $q->select('shows.id');
      }])
     ->select('episodes.id', 'episodes.season_id')
     ->get()

Or this :

$this->episode
     ->whereId($episode_id)
     ->with('season:seasons.id', 'show:shows.id')
     ->select('episodes.id', 'episodes.season_id')
     ->get()

Season work fine but shows send me this :
https://i.imgur.com/0M5q0vE.png

It's not that bad, but I want to know if it's normal or if i missed something.

Thanks in advance !

Missing column on query... scratching head!

Hi!

Have been trying to get this to work in my project.

A user can be assigned jobs (pivot table), each job has many areas, which can have many locations, and then once a job in a location is finished a completed model (with location_id) is created.

Initially I was storing user_id, location_id, area_id and job_id into the Completed table, however this was affecting seeding - then I found your project! Now just storing user_id and location_id

I've tried to get the amount of completed locations: $user->jobs()->withCount('completed'), however just get this error message:

SQLSTATE[42S22]: COLUMN NOT FOUND: 1054 unknown COLUMN 'locations.job_id' IN 'where clause' (SQL:
SELECT     `jobs`.*,
           (
                      SELECT     count(*)
                      FROM       `completeds`
                      INNER JOIN `locations`
                      ON         `locations`.`id` = `completeds`.`location_id`
                      WHERE      `jobs`.`id` = `locations`.`job_id`
                      AND        `completeds`.`deleted_at` IS NULL) AS `completeds_count`,
           `job_subs`.`user_id`                                     AS `pivot_user_id`,
           `job_subs`.`job_id`                                      AS `pivot_job_id`,
           `job_subs`.`created_at`                                  AS `pivot_created_at`,
           `job_subs`.`updated_at`                                  AS `pivot_updated_at`
FROM       `jobs`
INNER JOIN `job_subs`
ON         `jobs`.`id` = `job_subs`.`job_id`
WHERE      `job_subs`.`user_id` = 1
AND        `jobs`.`deleted_at` IS NULL)

I have all the belongsToThrough relations in place in the intermediate models, but it still looks for the _id field (which doesn't exist).

Any ideas? Am I just doing it wrong?

BelongsToMany -> BelongsToThrough

Is this posible to do?

User:
 - id
 - username
 
Posts:
 - id
 - user_id
 - comment_id

Comment:
 - id
 - review_id
 - message
 
 Review:
  - id
  - message

Can this be doeable on this package?

User - belongsToManay -> Post - belongsTo -> Comment - BelongsTo -> Review

Doesn't work for different DB connections

belongsToThrough doesn't work when 2 models are in two different databases. Native laravel functions like hasMany,BlongsTo,... work if you overwrite $connection in each model

Can't install on PHP 8

It's not possible to use this on Laravel 6 and PHP 8.
Laravel requires illuminate/database @ "self.version" which means they're using 6.x on Laravel 6.x:
https://github.com/laravel/framework/blob/006ba38124df6a8a651546a0301d604665b394b7/composer.json#L56

However this package requires illuminate/database version 8.

Steps to reproduce:

$ composer create-project laravel/laravel:"^6.20" example-app
$ cd example-app
$ composer require staudenmeir/belongs-to-through:"^2.11.1"

Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Root composer.json requires staudenmeir/belongs-to-through ^2.11.1 -> satisfiable by staudenmeir/belongs-to-through[v2.11.1].
    - staudenmeir/belongs-to-through v2.11.1 requires illuminate/database ^8.0 -> found illuminate/database[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.
Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Solution:

This package should require "illuminate/database": "^6.0|^7.0|^8.0".

BelongsToThrough with custom ForeignKey

I have structure table with custom foreignKey name owner_id

users:
  id: unsigned int, primary

properties:
  id : unsigned int, primary
  name: string
  owner_id: unsigned int, foreign(users)

periods:
  id: unsigned int, primary
  property_id : unsigned int, foreign(properties)
  date: date

activities:
  id : unsigned int, primary
  name : string
  period_id : unsigned int, foreign(periods)

but when i'm using BelongsToThrough relation:

class Activity {
    public function owner()
    {
        return $this->belongsToThrough('App\User',['App\Property','App\Period']);
    }
}

there's error because query search for user_id in table Property not owner_id.

is there any option that i could set custom foreignKey?

Problem Defining a Special Relation

This is probably not the best place for my question but it was the closest to the topic I could think of. So I hope there will be some hints however.

Is there any possibility to define the following call as a relation?

CustomerService::where([
    'customer_id' => $this->job->customer_id,
    'service_id' => $this->service_id,
])->first();

I have so far not been able to figure it out, because it's some kind of hybrid between belongsToThrough and a belongsTo relation with composite keys. I also use Compoships.

Thanks to your package I could at least already define the customer relation:

public function customer()
{
    return $this->belongsToThrough(
        User::class,
        Job::class,
    );
}

I would really like to benefit from the built-in query reduction, eager loading etc. that a relation would provide.

Here the database migrations:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
});

Schema::create('jobs', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('customer_id')->unsigned()->nullable()->index();
    $table->foreign('customer_id')->references('id')->on('users')->onDelete('cascade');
});

Schema::create('services', function (Blueprint $table) {
    $table->increments('id');
});

Schema::create('service_jobs', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('job_id')->unsigned()->index();
    $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade');
    $table->integer('service_id')->unsigned()->index();
    $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade');
});

Schema::create('customer_services', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('customer_id')->unsigned()->index();
    $table->foreign('customer_id')->references('id')->on('users')->onDelete('cascade');
    $table->integer('service_id')->unsigned()->index();
    $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade');
    $table->timestamps();
});

BelongsToThrough::associate()

"staudenmeir/belongs-to-through": "2.9",
PHP 7.2.26
Laravel Framework 6.18.19
I get this error on update:
Call to undefined method Znck\Eloquent\Relations\BelongsToThrough::associate()
and this is my relation methode:

 public function language() {
        return $this->belongsToThrough(\ModulMap::model('Language'), [\ModulMap::model('FaqCategory')], null,'', [\ModulMap::model('FaqCategory') => 'category_id'] );
 }

How to add pivot?

I saw this issue #42 but it might be related.

how can we add pivot for each for each traversed relationship for belongsToThrough

ID of result is the ID of the intermediate table instead

Meeting has many Question, which has many Answer

public function meeting() {
    return $this->hasOneThrough('Meeting','Question','id','id','question_id','meeting_id');
}

or

public function meeting() {
    return $this->belongsToThrough('Meeting','Question');
}

in both instances, the result Meeting model will have the ID of the intermediate Question model.

Laravel 6 and I installed your plugin ^2.5

Cannot instal on laravel 6.13.1

When I try to install this library I get this error:

Problem 1
- Installation request for staudenmeir/belongs-to-through 2.5 -> satisfiable by staudenmeir/belongs-to-through[v2.5].
- Conclusion: remove laravel/framework v6.13.1
- Conclusion: don't install laravel/framework v6.13.1
- staudenmeir/belongs-to-through v2.5 requires illuminate/database ~5.0 -> satisfiable by illuminate/database[5.0.x-dev, 5.1.x-dev, 5.2.x-dev, 5.3.x-dev, 5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev, 5.8.x-dev].
- don't install illuminate/database 5.8.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.4.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.5.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.6.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.7.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.0.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.1.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.2.x-dev|don't install laravel/framework v6.13.1
- don't install illuminate/database 5.3.x-dev|don't install laravel/framework v6.13.1
- Installation request for laravel/framework (locked at v6.13.1, required as ^6.2) -> satisfiable by laravel/framework[v6.13.1].

laravel nova get foreign key name

Hei im use your package on laravel nova to use belongs to dependency field
https://github.com/orlyapps/nova-belongsto-depend

which is i need to get higher parent without adding more field in my table .
that package i mention above is using more fk field to get higher parent
then i tried to use your package to make it more efficient

your package is worked perfectly when i use it with Tinker

image

but when i tried to use in Laravel nova or to combine with package above
im getting this error
image

this error showing up when on index page and create page

and btw nice works !

[asking] possible to support pivot table?

I often found cases where I need to retrieve the last record from many-to-many relationship.
For example in a users-subscriptions-podcasts case, I need to retrieve the last subscribed podcasts for a given user.
I would like to lazy load it via
$user->lastSubscribedPodcast
or from eager load
User::with('lastSubscribedPodcast')->get()

I've tried some combinations from belongsTo(), hasOne(), hasOneThrough(), and your belongsToThrough() but with no luck.

Do you have any idea to support this case?

Btw, thank you for your cool package!

belongsTo > HasMany > belongsTo

Hello!

I may be overcomplicating this, but some advice would be appreciated :-)

I have the following

ModelA -> belongsTo -> ModelB -> belongsTo ->modelC -> HasMany ->modelD -> belongsTo -> modelE

How could I define this?

I am trying to inverse the following

    return $this->hasManyDeepFromRelations($this->modelDrelationshipfunction(), (new ModelD)->modelc(), (new ModelC)->modelB(), (new ModelB)->modelArelationship());

Custom Local Key Names

It looks like support for custom local key column names was removed at some point.

It would be a breaking change but I have a local branch that would change the local keys parameter that is currently ignored into an array that would function similarly to the foreign key lookup array.

Currently this package isn't sufficient for complex relationships where some relationships don't rely on a model's primary key. Would you be open to releasing a new version that supports custom key names if I opened the PR?

BadMethodCallException

Laravel 5.0@homestead

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use \Znck\Eloquent\Relations\BelongsToThroughTrait;

    class Championship extends Model {

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

    public function country()
    {
        return $this->belongsToThrough('App\Country', 'App\MasterChampionship');
    }
}

artisan ticker:

App\Championship::first()->masterChampionship->country

gives correct result

App\Championship::first()->country

Gives
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::belongsToThrough()'

cant get it to work.

Hi,
this is what im trying to solve:
Country hasMany states
State hasMany Cities

so when i goto Cities it is connected to state which is connected to country but it doesn't seem to work.. here is my City model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class City extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;
    use CrudTrait;

    protected $table = 'citys';
    protected $primaryKey = 'id';

    public function state()
    {
        return $this->belongsTo('App\Models\State');
    }
    public function country()
    {
        return $this->belongsToThrough(Country::class, State::class);
    }
}

and my CityCrudController:

<?php namespace App\Http\Controllers\Admin;

use Backpack\CRUD\app\Http\Controllers\CrudController;

// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\CityRequest as StoreRequest;
use App\Http\Requests\CityRequest as UpdateRequest;

class CityCrudController extends CrudController {

    public function __construct() {
        parent::__construct();
        $this->crud->enableAjaxTable(); 

        $this->crud->setModel("App\Models\City");
        $this->crud->setRoute("admin/cities");
        $this->crud->setEntityNameStrings('City', 'Cities');

        $this->crud->addColumns([
                [
                    'name'  => 'name',
                    'label' => 'Name',
                    'type'  => 'text',
                ],
                [
                   // 1-n relationship
                   'label' => "State", // Table column heading
                   'type' => "select",
                   'name' => 'state_id', // the method that defines the relationship in your Model
                   'entity' => 'state', // the method that defines the relationship in your Model
                   'attribute' => "name", // foreign key attribute that is shown to user
                   'model' => "App\Models\State", // foreign key model
                ],
                [
                   // 1-n relationship
                   'label' => "Country", // Table column heading
                   'type' => "select",
                   'name' => 'country_id', // the method that defines the relationship in your Model
                   'entity' => 'country', // the method that defines the relationship in your Model
                   'attribute' => "name", // foreign key attribute that is shown to user
                   'model' => "App\Models\Country", // foreign key model
                ]
                              ]);
        $this->crud->addFields([
                [
                    'name'  => 'name',
                    'label' => 'Name',
                    'type'  => 'text',
                ],
                [
                   // 1-n relationship
                   'label' => "State", // Table column heading
                   'type' => "select",
                   'name' => 'state_id', // the method that defines the relationship in your Model
                   'entity' => 'state', // the method that defines the relationship in your Model
                   'attribute' => "name", // foreign key attribute that is shown to user
                   'model' => "App\Models\State", // foreign key model
                ],
                [
                   // 1-n relationship
                   'label' => "Country", // Table column heading
                   'type' => "select",
                   'name' => 'country_id', // the method that defines the relationship in your Model
                   'entity' => 'country', // the method that defines the relationship in your Model
                   'attribute' => "name", // foreign key attribute that is shown to user
                   'model' => "App\Models\Country", // foreign key model
                ]
                              ]);
    }

    public function store(StoreRequest $request)
    {
        return parent::storeCrud();
    }

    public function update(UpdateRequest $request)
    {
        return parent::updateCrud();
    }
}

can you please tell me where am i going wrong.
thanks.

Possibly unnecessary LOC

This line of code is not covered by any of the tests.

...
            if ($lastIndex === $index) {
                $prev = $this->prefix.$prev; // TODO: Check if this line is really necessary. Its not covered by any of the tests.
            }
...

Is it required in some condition or can be dropped?

Does this work?

I'm just getting a blank version of the related model back (i.e. an instance, but with no attributes)

extra bindings bug

here is what i have

tables

  • service
    id

  • service_infos
    id
    service_id

  • service_request
    id
    service_info_id

models

  • service
public function requests()
{
    return $this->hasManyThrough(ServiceRequest::class, ServiceInfo::class);
}
  • service request
public function service()
{
    return $this->belongsToThrough(Service::class, ServiceInfo::class);
}

test

DB::connection()->enableQueryLog();
ServiceRequest::with('service')->first(); // service = null;
dd(DB::getQueryLog());
"query" => "select `services`.*, `service_infos`.`id` as `laravel_through_key` from `services` inner join `service_infos` on `service_infos`.`service_id` = `services`.`id` where `service_infos`.`id` in (?) ◀"
"bindings" => array:2 [
    0 => "App\Models\Service"
    1 => "144cbcea-2ce1-46a2-b438-50bd3f25ebfb"
]
"time" => 0.0

am not sure if am doing something wrong from my part or its a bug with the package, any help is appreciated.

withTrashed doesn't work for destination model

In my model I have relation like that:

return $this->belongsToThrough(
    Project::class,
    Asset::class
)->withTrashed();

But withTrashed doesn't work with Project model that has a SoftDeletes trait. As I can see from a query log, deleted_at is null is still added to a query.

use through in sub category table

hi
a'm use this package and try get sub category of product same below:
Category → Has many → Category → Has many → Product

in category model

public function products()
    {
        return $this->hasMany(Product::class);
    }

and get parent category of product same this in product model:

public function parentCategory()
    {
        return $this->belongsToThrough(Category::class, [Category::class]);
    }

    /**
     * relation product with category one to many.
     * @return BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

but this error:

Syntax error or access violation: 1066 Not unique table/alias: 'categories' (SQL: select `categories`.* from `categories` inner join `categories` on `categories`.`category_id` = `categories`.`id` where `categories`.`id` = 7 limit 1)

in staudenmeir/eloquent-has-many-deep package use Table Aliases trait but in this package not use, please set this trait in this package

LocalKey being ignored

On the Znck\Eloquent\Relations\BelongsToThrough constructor, it allows you to specify a local key, however this appears to be being completely ignored.

Newest version breaks whereHas on Laravel 5.2

Since version 2.3, wherehas returns an error when using a query like this:

$account->brands()->whereHas('user', function ($query) use ($user) {
	$query->where('users.id', $user->id);
})->first();

the error itself:

'BadMethodCallException' with message 'Call to undefined method Illuminate\Database\Query\Builder::getHasCompareKey()' in /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2405
Stack trace:
#0 [internal function]: Illuminate\Database\Query\Builder->__call('getHasCompareKe...', Array)
#1 [internal function]: Illuminate\Database\Query\Builder->getHasCompareKey()
#2 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1426): call_user_func_array(Array, Array)
#3 [internal function]: Illuminate\Database\Eloquent\Builder->__call('getHasCompareKe...', Array)
#4 [internal function]: Illuminate\Database\Eloquent\Builder->getHasCompareKey()
#5 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php(343): call_user_func_array(Array, Array)
#6 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php(165): Illuminate\Database\Eloquent\Relations\Relation->__call('getHasCompareKe...', Array)
#7 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php(165): Znck\Eloquent\Relations\BelongsToThrough->getHasCompareKey()
#8 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(823): Illuminate\Database\Eloquent\Relations\Relation->getRelationQuery(Object(Illuminate\Database\Eloquent\Builder), Object(Illuminate\Database\Eloquent\Builder))
#9 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(886): Illuminate\Database\Eloquent\Builder->has('user', '>=', 1, 'and', Object(Closure))
#10 [internal function]: Illuminate\Database\Eloquent\Builder->whereHas('user', Object(Closure))
#11 /home/digitaloctoapp/public_html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php(343): call_user_func_array(Array, Array)
#12 /home/digitaloctoapp/public_html/app/Console/Commands/AccountSummary.php(178): Illuminate\Database\Eloquent\Relations\Relation->__call('whereHas', Array)
#13 /home/digitaloctoapp/public_html/app/Console/Commands/AccountSummary.php(178): Illuminate\Database\Eloquent\Relations\BelongsToMany->whereHas('user', Object(Closure))
#14 [internal function]: App\Console\Commands\AccountSummary->handle()

Reverted back to 2.2.2 and everything works as expected

Documentation needs updating

use \Znck\Eloquent\Relations\BelongsToThroughTrait;

needs to change to

use \Znck\Eloquent\Traits\BelongsToThrough;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.